using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
//using System.Web.Mail;
using System.Net.Mail;
using System.Globalization;
using System.Threading;
using System.Resources;
using System.Text;
/****************************************************************************************************************************
* Project Name    : TimeCheck                         Started Date  : 12-Aug-2007
* Module          : Permission Application            Last Modified : 14-Aug-2007
* Programmer      : Prabakaran.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_LeavePermissionModify : Base.BasePage
{
    #region ForEastman
    internal enum permissionHeader
    {
        FIRST = 1,
        SECOND = 2,
        THIRD = 3,
        FOURTH = 4,
        FIFTH = 5
    }
    Panel pn = new Panel();
    DataSet prevDs = new DataSet();
    #endregion
    #region "Variable Declaration"
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    //Cls_Connect cl = new Cls_Connect();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    LeaveEventData objLeaveEventData = new LeaveEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    SMSNotification objsms = new SMSNotification();
    cls_Common objClassCommon = new cls_Common();
    DataSet ds_LeaveType = new DataSet();
    DataSet ds_PermissionApplication = new DataSet();
    DataSet ds_Prev_PermissionApplication = new DataSet();
    DataSet ds_RemainingDays = new DataSet();
    DataSet ds_HoursAlreadyTaken = new DataSet();
    DataSet ds_CheckLeaveApplication = new DataSet();
    DataSet ds_MaxNoOfHours = new DataSet();
    DataSet dsEmailIdOfSanctionAuthority = new DataSet();
    DataSet ds_EmailIdOfReportingTo = new DataSet();
    DataSet ds_EmployeeDetails = new DataSet();
    DataSet ds_Year = new DataSet();
    string strFromTime, strEndTime, strReason, EmployeeEamilId, strFromEmailId, strEmailIdReportingTo, gstrDateFormat, gstrTimeFormat, strApplicationDate, strFromDateTime, strToDateTime, strlevelName;
    string MaxPermitHours, strStatusType;
    int iLeavePermission_Id, iEmployeeID, iPermissionType_Id, mEmployeeId, StartYear, EndYear;
    //int count;
    //double   dNoOfHoursAlreadyTaken ;
    //string strEmailIdSanctionAuthority;
    string dNumberOfHoursApplied, dNoOfRemainingHours, EmpID;
    //Double  intervalHours;
    bool checkEmail = true, blnCheckSMS = true;
    int iModifyFlag = 0;
    int payrollConfig = 0;
    //double CL;
    //double SL;
    //double EL;
    int permissionSanctionExists = 0;
    int approvalSettingsPageExists = 0;
    string gstrYearSettingStartDate = string.Empty;
    string gstrYearSettingsEndDate = string.Empty;
    DataSet ds_NextYear = new DataSet();
    string gstrNextYearSettingStartDate = string.Empty;
    string gstrNextYearSettingsEndDate = string.Empty;
    string strHtml = string.Empty;
    Int64 intPermissionId = 0;
    Int64 intLevelId = 0;
    #endregion
    protected override void Page_Load(object sender, EventArgs e)
    {
        if (Request.UrlReferrer != null)
        {
            string GetURL = Convert.ToString(Request.UrlReferrer);
        }
        else
        {
            Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
        }
        // session checking
        payrollConfig = objClassCommon.CheckPageExistsInLicense(185);
        base.Page_Load(sender, e);
        //get the culture info to set the language      
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alery_PermissionDay", ci) + "','" + rm.GetString("Alert_StartTime", ci) + "','" + rm.GetString("Alert_EndTime", ci) + "','" + rm.GetString("Alert_FillReasons", ci) + "','" + rm.GetString("Alert_PermissionHoursEmpty", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessagesAjax_Permission('" + rm.GetString("lblSelectEmployee", ci) + "','" + rm.GetString("Alert_SelectvalidPermissionDate", ci) + "','" + rm.GetString("Alert_SelectvalidPermissionFromDateandTime", ci) + "','" + rm.GetString("Alert_SelectvalidPermissionFromDateandTime", ci) + "','" + rm.GetString("Master_Holiday_Select_Valid_Year", ci) + "','" + rm.GetString("ALert_Permissionshouldnotbeappliedbeforedateofjoining", ci) + "','" + rm.GetString("Alert_PermissionHoursfallsonWeeklyOffGlobalHoliday", ci) + "','" + rm.GetString("Alert_SelectValidPermissionHours", ci) + "','" + rm.GetString("Report_ShiftNotAllocated", ci) + "','" + rm.GetString("Alert_PermissionHoursdoesnotfallinsidetheshift", ci) + "','" + rm.GetString("ALert_PermissionHoursfallwiththeshiftbreaktimes", ci) + "','" + rm.GetString("ALert_PermissionHoursShouldNotInNegativeHours", ci) + "','" + rm.GetString("Alert_PermissionHoursNotdefinedforthisemployee", ci) + "','" + rm.GetString("Alert_MaxNumberofInstancespermonthExceeds", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_ValiddateDateDDMMYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddateDateDDMMYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Set UserRights
        UserRights();
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        ds_Year = objClassCommon.GetYearsetting();
        if (ds_Year.Tables[0].Rows.Count <= 0)
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Msg_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertLeavePolicyYear", strScript);
        }
        else
        {
            StartYear = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["StartYear"]);
            EndYear = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["EndYear"]);
            gstrYearSettingStartDate = Convert.ToString(ds_Year.Tables[0].Rows[0]["FromDate"]);
            gstrYearSettingsEndDate = Convert.ToString(ds_Year.Tables[0].Rows[0]["ToDate"]);
            ViewState["YearSettings_Id"] = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettings_Id"]);
            ds_Year.Dispose();
        }
        //Fill the next Year Settings Detail
        ds_NextYear = objClassCommon.GetNextYearsetting();
        if (ds_NextYear.Tables[0].Rows.Count > 0)
        {
            gstrNextYearSettingStartDate = Convert.ToString(ds_NextYear.Tables[0].Rows[0]["FromDate"]);
            gstrNextYearSettingsEndDate = Convert.ToString(ds_NextYear.Tables[0].Rows[0]["ToDate"]);
            ViewState["NextYearSettings_Id"] = Convert.ToString(ds_NextYear.Tables[0].Rows[0]["YearSettings_Id"]);
            ds_NextYear.Dispose();
        }
        //btn_Modify.Attributes.Add("onclick", "return Validation()");
        // btn_Delete.OnClientClick = "return confirm('" + rm.GetString("Alert_ConfirmDelete", ci) + "')";
        iLeavePermission_Id = int.Parse(Request.QueryString["Permission_Id"]);
        if (!Page.IsPostBack)
        {
            if (Session["SanctionUrl"] != null)
            {
                Session["SanctionUrl"] = null;
            }
            ViewDetails();
            GetEmployeeName();
            CheckRemainingHours();
            // ddl_LeaveType.Focus();
            ControlCreation();
        }
        DataSet dsEmployeeGroup = new DataSet();
        dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));
        if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
        {
            Session["UserGroupName"] = Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["GroupName"]);
        }
    }
    /// <summary>
    /// Get Employee Name based on EmployeeId
    /// </summary>
    public void GetEmployeeName()
    {
        if (Session["user"] == null || Convert.ToString(Session["user"]) == string.Empty)
        {
            Response.Redirect("../Index.aspx");
        }
        else
        {
            string strEmpFirstName, strEmpLastName;
            ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(mEmployeeId);
            ViewState["LevelId"] = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"]);
            ViewState["DesignationId"] = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["DesignationId"]);
            strFromEmailId = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["EmailId"]);
            strEmpFirstName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
            strEmpLastName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
            lbl_EmployeeID.Text = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
            iEmployeeID = Convert.ToInt32(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Id"]);
            ViewState["vEmployeeId"] = Convert.ToString(iEmployeeID);
            lbl_EmployeeName.Text = strEmpFirstName + " " + strEmpLastName;
            ViewState["vsEmpID"] = lbl_EmployeeID.Text;
            ViewState["vsEmpFirstName"] = strEmpFirstName;
            ViewState["vsEmpLastName"] = strEmpLastName;
            ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(iEmployeeID));
            if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
            {
                strlevelName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["levelName"]);
                ViewState["vslevelName"] = strlevelName;
            }
            else
            {
                ViewState["vslevelName"] = "";
            }
        }
    }
    /// <summary>
    /// Diplay the permission Details
    /// </summary>
    public void ViewDetails()
    {
        ds_PermissionApplication = objPermissionEventData.SelectLeavePermissionByPermissionId(iLeavePermission_Id);
        string strStartTime = "";
        string reverse = "";
        Session["Prev_PermissionDetails"] = null;
        if (ds_PermissionApplication.Tables[0].Rows.Count > 0)
        {
            ViewState["PermisisonBeforeModify"] = ds_PermissionApplication.Tables[0];
            mEmployeeId = Convert.ToInt32(ds_PermissionApplication.Tables[0].Rows[0]["Employee_Id"]);
            hdnEmployeeId.Value = Convert.ToString(mEmployeeId);
            ViewState["StatusOfPermission"] = Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_Status"]);
            lbl_EmployeeID.Text = Convert.ToString(iEmployeeID);
            lbl_PermissionApplicationDate.Text = (DateTime.Parse(Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_AppliedDate"]))).ToString(Convert.ToString(Session["MDateFormat"]));
            TxtPermissionDate.Text = (DateTime.Parse(Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_Date"]))).ToString(Convert.ToString(Session["MDateFormat"]));
            string strDateTimeFormat = Convert.ToString(Session["MDateFormat"]) + " " + Convert.ToString(Session["MTimeFormat"]);
            strStartTime = Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_FromTime"]);
            string strEndTime = Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_ToTime"]);
            txt_StartTime.Text = Convert.ToDateTime(strStartTime).ToString(strDateTimeFormat);
            txt_EndTime.Text = Convert.ToDateTime(strEndTime).ToString(strDateTimeFormat);
            //-->End
            reverse = Convert.ToString(txt_EndTime.Text).Substring(txt_EndTime.Text.Length - 5);
            ViewState["vPermissionFromTime"] = txt_StartTime.Text;
            ViewState["vPermissionToTime"] = txt_EndTime.Text;
            txtReason.Text = Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_Reason"]);
            ViewState["vReason"] = txtReason.Text;
            iPermissionType_Id = Convert.ToInt32(ds_PermissionApplication.Tables[0].Rows[0]["Permission_Type"]);
            txtApprovalCC.Text = Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["CcMail"]);
            EmployeeEamilId = Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["EmailId"]);
            ViewState["vsEmployeeEamilId"] = EmployeeEamilId;
            // ddl_PermissionType.Items.Add(iPermissionTypeId.ToString());
            //ddl_PermissionType.SelectedIndex = iPermissionType_Id;
            TimeDifference(txt_StartTime.Text, txt_EndTime.Text, Convert.ToString(ds_PermissionApplication.Tables[0].Rows[0]["Permission_Hours"]));
            DataSet ds_PermissionConversation = new DataSet();
            ds_PermissionConversation = objPermissionEventData.GetPermissionConversation(iLeavePermission_Id);
            if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
            {
                ViewState["vwReplyToPerson"] = Convert.ToString(ds_PermissionConversation.Tables[0].Rows[0]["CommentsBy"]);
            }
            else
            {
                ViewState["vwReplyToPerson"] = string.Empty;
            }
            if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
            {
                btn_Modify.Text = "&nbsp;&nbsp;REPLY";
            }
        }
        #region Eastman
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToString(Session["packageID"]) == "155")
            {
                btn_Modify.Visible = false;
                btn_print.Visible = true;
                ds_Prev_PermissionApplication = objPermissionEventData.SelectPermissionDetailsUsingIDForPrint_Eastman(Convert.ToDouble(iLeavePermission_Id));
                if (ds_Prev_PermissionApplication.Tables[0].Rows.Count > 0)
                {
                    grv_Employees.DataSource = ds_Prev_PermissionApplication;
                    grv_Employees.DataBind();
                    prevDs = ds_Prev_PermissionApplication.Copy();
                }
                if (prevDs != null)
                {
                    if (prevDs.Tables.Count > 0)
                    {
                        DataTable dt = prevDs.Tables[0];
                        DataRow dr = dt.NewRow();
                        dr["Permission_Id"] = Convert.ToString(iLeavePermission_Id);
                        dr["Permission_Date"] = Convert.ToString(TxtPermissionDate.Text);
                        dr["Permission_FromTime"] = Convert.ToString(txt_StartTime.Text);
                        dr["Permission_ToTime"] = Convert.ToString(reverse);
                        dr["Permission_Reason"] = Convert.ToString(txtReason.Text);
                        dr["No_Of_Hours"] = Convert.ToString(txt_NumberOfHours.Text);
                        dr["Permission_AppliedDate"] = Convert.ToString(lbl_PermissionApplicationDate.Text);
                        dt.Rows.Add(dr);
                        dt.AcceptChanges();
                    }
                    else
                    {
                        DataTable dt = new DataTable();
                        DataRow dr = dt.NewRow();
                        dt.Columns.Add("Permission_Id", typeof(string));
                        dt.Columns.Add("Permission_Date", typeof(string));
                        dt.Columns.Add("Permission_FromTime", typeof(string));
                        dt.Columns.Add("Permission_ToTime", typeof(string));
                        dt.Columns.Add("Permission_Reason", typeof(string));
                        dt.Columns.Add("No_Of_Hours", typeof(string));
                        dt.Columns.Add("Permission_AppliedDate", typeof(string));
                        dt.Rows.Add(Convert.ToString(intPermissionId), Convert.ToString(TxtPermissionDate.Text), Convert.ToString(txt_StartTime.Text), Convert.ToString(reverse), Convert.ToString(txtReason.Text), Convert.ToString(txt_NumberOfHours.Text), Convert.ToString(lbl_PermissionApplicationDate.Text));
                        prevDs.Tables.Clear();
                        prevDs.Tables.Add(dt);
                    }
                    Session["Prev_PermissionDetails"] = prevDs;
                }
            }
        #endregion
    }
    /// <summary>
    /// Find the difference between Permission from time and End time
    /// </summary>
    /// <param name="d1"></param>
    /// <param name="d2"></param>
    /// <returns></returns> 
    public void TimeDifference(string FromTime, string EndTime, string PermissionHours)
    {
        //Convert Date Format to MM/dd/yyyy Format
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]); // christopher added
        // strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
        //Convert Date Format to MM/dd/yyyy Format // christopher commented
        //strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), FromTime, "B"); 
        //strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), EndTime, "B");
        // christopher added
        strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), FromTime, "B");
        strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), EndTime, "B");
        //TimeSpan tsStartTime = DateTime.Parse(FromTime).TimeOfDay;
        //TimeSpan tsEndTime = DateTime.Parse(EndTime).TimeOfDay;
        TimeSpan tsDiff = new TimeSpan();
        DateTime dtmIn = DateTime.Parse(strFromDateTime);
        DateTime dtmOut = DateTime.Parse(strToDateTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = Convert.ToString(tsDiff);
        int sReturn = s.LastIndexOf(':');
        string RemainHours = PermissionHours;
        ViewState["PreviousHours"] = RemainHours;
        //Adding datetime format and changed as like in product for avoiding datetime format error
        string strPermissionDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
        ds_MaxNoOfHours = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(mEmployeeId);
        //ds_MaxNoOfHours = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(Convert.ToInt32(Session.Contents["EmpAutoId"]));
        foreach (DataRow dRow in ds_MaxNoOfHours.Tables[0].Rows)
        {
            MaxPermitHours = Convert.ToString(dRow["Permission_MaxHrs_Month"]);
        }
        //string[] MaxPermissionHours = MaxPermitHours.Split(':');
        //MaxPermitHours = MaxPermissionHours[0] + "." + MaxPermissionHours[1];
        //intervalHours = Convert.ToDouble(MaxPermitHours) - Convert.ToDouble(tsDiff.Hours);
        txt_NumberOfHours.Text = RemainHours;
        lblRemainNoOfHours.Text = MaxPermitHours;
    }
    /// <summary>
    /// Find the difference between From Date and End Date
    /// </summary>
    /// <param name="d1"></param>
    /// <param name="d2"></param>
    /// <returns></returns>
    public int DateDifference(DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        int Days = (ts.Days) + 1;
        return Days;
    }
    /// <summary>
    /// Calculate the Number of permission hours applied
    /// </summary>
    /// <returns></returns>
    public string CalculateNumberOfHoursApplied(string startTime, string EndTime)
    {
        //TimeSpan tsStartTime = DateTime.Parse(txt_StartTime.Text).TimeOfDay;
        //TimeSpan tsEndTime = DateTime.Parse(txt_EndTime.Text).TimeOfDay;
        TimeSpan tsDiff = new TimeSpan();
        DateTime dtmIn = DateTime.Parse(startTime);
        DateTime dtmOut = DateTime.Parse(EndTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = Convert.ToString(tsDiff);
        int sReturn = s.LastIndexOf(':');
        string RemainHours = s.Remove(sReturn);
        //tsDiff = tsEndTime.Subtract(tsStartTime);
        //int iDays = DateDifference(DateTime.Parse(txtToDate.Text), DateTime.Parse(txtFromDate.Text));
        //  double dDays = Double.Parse(iDays.ToString());
        return (RemainHours);
    }
    /// <summary>
    /// Calculate the reamining number of hours
    /// </summary>
    /// <param name="NoOfHoursApplied"></param>
    /// <param name="TotNoOfRemainingHours"></param>
    public void CheckHours(string NoOfHoursApplied, string TotNoOfRemainingHours)
    {
        //if (NoOfHoursApplied > TotNoOfRemainingHours)
        //{
        //    lbl_Error.Text = "You have exceeded the Permission Hours Limit";
        //    iModifyFlag = 1;
        //    return;
        //}
        //else if (NoOfHoursApplied <= 0)
        //{
        //    lbl_Error.Text = "Select Valid Hours";
        //    iModifyFlag = 1;
        //    return;
        //}
        // TimeSpan tsTotalHoursRemaining = new TimeSpan();
        // TimeSpan tsPreviousHours = new TimeSpan();
        // tsTotalHoursRemaining = DateTime.Parse(TotNoOfRemainingHours).TimeOfDay;
        // tsPreviousHours = DateTime.Parse(ViewState["PreviousHours"].ToString()).TimeOfDay;
        //// tsTotalHoursRemaining = DateTime.Parse(ViewState["PreviousHours"].ToString()).Subtract(DateTime.Parse(TotNoOfRemainingHours));
        // tsTotalHoursRemaining = tsTotalHoursRemaining.Add(tsPreviousHours);
        // TimeSpan dsDiff= new TimeSpan();
        // dsDiff = DateTime.Parse(NoOfHoursApplied).TimeOfDay;
        // dsDiff = tsTotalHoursRemaining.Subtract(dsDiff);
        // //dsDiff = DateTime.Parse(NoOfHoursApplied).Subtract(DateTime.Parse(TotNoOfRemainingHours));
        //DateTime NoOfHours = DateTime.Parse(NoOfHoursApplied);
        int intNoOfHoursApplied = ConvertHoursToMinutes(NoOfHoursApplied);
        int intTotNoOfRemainingHours = ConvertHoursToMinutes(TotNoOfRemainingHours);
        int intPreviousHours = ConvertHoursToMinutes(Convert.ToString(ViewState["PreviousHours"]));
        int intTotalHours = 0;
        intTotNoOfRemainingHours = intTotNoOfRemainingHours + intPreviousHours;
        intTotalHours = intTotNoOfRemainingHours - intNoOfHoursApplied;
        if (intTotalHours < 0)
        {
            //lbl_Error.Text = "You have exceeded the Permission Hours Limit";
            base.Message(rm.GetString("Msg_ExceedPermissionHour", ci));
            iModifyFlag = -1;
            return;
        }
        else if (intNoOfHoursApplied <= 0)
        {
            //lbl_Error.Text = "Select Valid Hours";
            base.Message(rm.GetString("Msg_ValidHour", ci));
            iModifyFlag = -1;
            return;
        }
        //Adding datetime format and changed as like in product for avoiding datetime format error
        string strPermissionDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
        ds_MaxNoOfHours = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(iEmployeeID);
        ds_HoursAlreadyTaken = objPermissionEventData.GetHoursAlreadyTaken(mEmployeeId, DateTime.Parse(strApplicationDate));
        TimeSpan tsPermission_MaxHrs_Instance = new TimeSpan();
        string Permission_MaxHrs_Instance = Convert.ToString(ds_MaxNoOfHours.Tables[0].Rows[0]["Permission_MaxHrs_Instance"]);
        string nHrs = txt_NumberOfHours.Text;
        tsPermission_MaxHrs_Instance = DateTime.Parse(Permission_MaxHrs_Instance).Subtract(DateTime.Parse(nHrs));
        if (tsPermission_MaxHrs_Instance.TotalHours < 0)
        {
            iModifyFlag = -1;
            //lbl_Error.Text = "Your Maximum Number of Hours per Instance is" + " " + Permission_MaxHrs_Instance;
            base.Message(rm.GetString("Msg_MaxNoOfHrsInstance", ci) + " " + Permission_MaxHrs_Instance + "");
            //lblRemainNoOfHours.Text = "00:00";
            return;
        }
    }
    public int ConvertHoursToMinutes(string strHours)
    {
        string[] mins;
        mins = strHours.Split(':');
        string minsStr, totalMinsStr;
        int minsInt, totalMinsInt = 0;
        minsStr = Convert.ToString(mins[0]);
        minsInt = Convert.ToInt32(minsStr) * 60;
        totalMinsInt = minsInt + Convert.ToInt32(mins[1]);
        return totalMinsInt;
    }
    /// <summary>
    /// Find the remaining number of permission hours
    /// </summary>
    public void CheckRemainingHours()
    {
        //ds_MaxNoOfHours = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(Convert.ToInt32(Session.Contents["EmpAutoId"]));
        string strPermissionDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
        ds_MaxNoOfHours = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(mEmployeeId);
        if (ds_MaxNoOfHours.Tables[0].Rows.Count != 0)
        {
            foreach (DataRow dRow in ds_MaxNoOfHours.Tables[0].Rows)
            {
                if (dRow["Permission_MaxHrs_Month"] != null)
                {
                    MaxPermitHours = Convert.ToString(dRow["Permission_MaxHrs_Month"]);
                }
                else
                {
                    MaxPermitHours = "00:00";
                }
            }
            //Convert Date Format to MM/dd/yyyy Format
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
            //string strPermissionDate=
            ds_HoursAlreadyTaken = objPermissionEventData.GetHoursAlreadyTaken(mEmployeeId, DateTime.Parse(strApplicationDate));
            TimeSpan diffHours;
            //diffHours = DateTime.Parse(MaxPermitHours).Subtract(DateTime.Parse(ds_HoursAlreadyTaken.Tables[0].Rows[0]["HoursTakenInMinutes"].ToString()));
            double MaxPermitHours_Mins = ConvertHoursMinsToMinutes(MaxPermitHours);
            double HoursTakenInMinutes_Mins = ConvertHoursMinsToMinutes(Convert.ToString(ds_HoursAlreadyTaken.Tables[0].Rows[0]["HoursTakenInMinutes"]));
            double diffHours_Mins = MaxPermitHours_Mins - HoursTakenInMinutes_Mins;
            //diffHours = DateTime.Parse(MaxPermitHours).Subtract(DateTime.Parse(ds_HoursAlreadyTaken.Tables[0].Rows[0]["HoursTakenInMinutes"].ToString()));
            string s;
            s = ConvertMinutesToHoursMins(diffHours_Mins);
            int sReturn = s.LastIndexOf(':');
            string RemainHours = s;
            //s.Remove(sReturn);
            lblRemainNoOfHours.Text = RemainHours;
        }
    }
    protected void btn_Modify_Click(object sender, EventArgs e)
    {
        //This Line Add for the approval data not modify. Added by karthikeyan.R 
        if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" && Convert.ToString(Session["HasSpecialRights"]) != "True")
        {
            ControlCreation();
            if (Convert.ToString(ViewState["StatusOfPermission"]) == "Approved" || Convert.ToString(ViewState["StatusOfPermission"]) == "Forwarded")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_CannotmodifythisrecordPermission", ci) + "');", true);
                //Page.RegisterStartupScript("statusalertModifyPer", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotmodifythisrecord", ci) + "');</script>");
                return;
            }
        }
        if (lblRemainNoOfHours.Text != string.Empty)
        {
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" && Convert.ToString(Session["HasSpecialRights"]) != "True")
            {
                if ((Convert.ToDateTime(objClassCommon.DateConvertion((gstrDateFormat), TxtPermissionDate.Text))) < Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                {
                    string strScript = string.Empty;
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "alert('" + rm.GetString("Permission_PastDate", ci) + "');location.href='TA_UI_Transactions_LeavePermission.aspx';";
                    strScript = strScript + "</script>";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                    return;
                }
            }
            if (Page.IsValid == true)
            {
                string strLengthCheck = txtReason.Text.Trim().Replace("'", "''");
                if (strLengthCheck.Length > 1000)
                {
                    Message("Maximum character for Reason is 1000");
                    return;
                }
                //Convert Date Format to MM/dd/yyyy Format
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]); // christopher added
                // christopher added
                strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), txt_StartTime.Text, "B");
                strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), txt_EndTime.Text, "B");
                int LeaveStartYear = DateTime.Parse(strFromDateTime).Year;
                int LeaveEndYear = DateTime.Parse(strToDateTime).Year;
                if ((LeaveStartYear >= StartYear && LeaveStartYear <= EndYear) && (LeaveEndYear >= StartYear && LeaveEndYear <= EndYear))
                {
                }
                else
                {
                    lbl_Error.Text = rm.GetString("Master_Holiday_Select_Valid_Year", ci);
                    return;
                }
                //Validate less than Year settings
                if ((DateTime.Parse(strApplicationDate)) < (DateTime.Parse(gstrYearSettingStartDate)))
                {
                    Message("Permission duration should not be less than the current year");
                    return;
                }
                //Validate permission beyond the next year setting
                if (ViewState["NextYearSettings_Id"] != null || Convert.ToString(ViewState["NextYearSettings_Id"]) != string.Empty)
                {
                    if (DateTime.Parse(strApplicationDate) > DateTime.Parse(gstrNextYearSettingsEndDate))
                    {
                        Message("Permission application cannot be raised beyond the next year");
                        return;
                    }
                }
                else
                {
                    if (DateTime.Parse(strApplicationDate) > DateTime.Parse(gstrYearSettingsEndDate))
                    {
                        Message("Permission application cannot be raised beyond the current year");
                        return;
                    }
                }
                int CurrentYearLeaveCount = 0;
                int NextYearLeaveCount = 0;
                if (DateTime.Parse(strApplicationDate) <= DateTime.Parse(gstrYearSettingsEndDate))
                {
                    CurrentYearLeaveCount = 1;
                }
                else if (DateTime.Parse(strApplicationDate) >= DateTime.Parse(gstrNextYearSettingStartDate))
                {
                    NextYearLeaveCount = 1;
                }
                string YearSettingIDforSave = string.Empty;
                if (CurrentYearLeaveCount == 1)
                {
                    YearSettingIDforSave = Convert.ToString(ViewState["YearSettings_Id"]);
                }
                else if (NextYearLeaveCount == 1)
                {
                    YearSettingIDforSave = Convert.ToString(ViewState["NextYearSettings_Id"]);
                }
                iEmployeeID = Convert.ToInt32(hdnEmployeeId.Value);
                //Declare Permission Status
                string strPermissionStatus = string.Empty;
                string strPermissionStatusNew = string.Empty;
                ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(iEmployeeID);
                dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(iEmployeeID);
                bool blnAllowModify = false;
                if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0 && dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                {
                    if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value && dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                    {
                        if (Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != "" && Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != "")
                        {
                            if (Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) == Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]))
                            {
                                blnAllowModify = true;
                            }
                        }
                    }
                }
                //Check Approval Settings for EnterPrise Edition and Demo Version
                // Demo Edition - 0
                //Standard Edition -  1
                //Profession Edition - 2
                //Enterprise Edition - 3
                //Declare Permission Status                
                int payrollConfig = 0;
                /*Added New parameter(Max Days/Month)for Angler. For this we are checking whether the payroll configuration page is exists or not*/
                payrollConfig = objClassCommon.CheckPageExistsInLicense(185);
                /*Below parameter is used for Angler*/
                if (payrollConfig == 0)
                {
                    permissionSanctionExists = objClassCommon.CheckPageExistsInLicense(248);
                }
                else
                {
                    permissionSanctionExists = objClassCommon.CheckPageExistsInLicense(110);
                }
                //Checking grade module is available or not and changed the id value from 110 to 228
                approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
                //if (Session["Edition"].ToString() == "0" || Session["Edition"].ToString() == "3")
                if (permissionSanctionExists == 1)
                {
                    if (approvalSettingsPageExists == 1)
                    {
                        //Get Compnay Id of the Employeee
                        int intCompanyId = base.GetCompanyId(iEmployeeID);
                        //Get Approval Settings Based on Company Id
                        DataSet dsApprovalSettings = new DataSet();
                        ShiftEvenData objShift = new ShiftEvenData();
                        dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
                        if (dsApprovalSettings != null)
                        {
                            if (dsApprovalSettings.Tables.Count > 0)
                            {
                                if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                                {
                                    if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["PermissionSanction"]) == false)
                                    {
                                        strPermissionStatus = "Approved";
                                    }
                                    else
                                    {
                                        if (Convert.ToString(Session["ReportsBasedOn"]) != string.Empty)
                                        {
                                            strPermissionStatusNew = objShift.GetApprovalStatus(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(hdnEmployeeId.Value), Convert.ToBoolean(Session["ReportsBasedOn"]));
                                            if (strPermissionStatusNew != string.Empty && strPermissionStatusNew != null)
                                            {
                                                strPermissionStatus = strPermissionStatusNew;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ApprovalSettings", ci) + "');", true);
                                    //  base.Message(rm.GetString("Msg_ApprovalSettings", ci));
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    strPermissionStatus = "Approved";
                }
                if (Convert.ToString(ViewState["StatusOfPermission"]) == "Pending")
                {
                }
                else if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
                {
                }
                else
                {
                    if (strPermissionStatus == "Approved")
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_CannotmodifythisrecordPermission", ci) + "');", true);
                        //Page.RegisterStartupScript("statusalertModifyPer", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotmodifythisrecord", ci) + "');</script>");
                        return;
                    }
                    if (strPermissionStatus != "Approved")
                    {
                        if (blnAllowModify == true)
                        {
                        }
                        else
                        {
                            //Page.RegisterStartupScript("statusalertModifyPer", "<script language='javascript'>alert('Cannot modify this record');</script>");
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_CannotmodifythisrecordPermission", ci) + "');", true);
                            return;
                        }
                    }
                }
                ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
                if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
                {
                    strlevelName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["levelName"]);
                    EmpID = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_id"]);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("lblSelectEmployee", ci) + "');", true);
                    //lbl_Error.Text = "Select Employee";
                    //base.Message(rm.GetString("lblSelectEmployee", ci));
                    return;
                }
                dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                txt_NumberOfHours.Text = Convert.ToString(dNumberOfHoursApplied);
                dNoOfRemainingHours = lblRemainNoOfHours.Text;
                //dTotalHours = dNoOfHoursTaken - dNumberOfHoursApplied;
                CheckHours(dNumberOfHoursApplied, dNoOfRemainingHours);
                int count = 0;
                //Check Permission Before Leave
                DataSet dsLeaveDetails = new DataSet();
                string PermissionStatus;
                DataSet dsShiftid = new DataSet();
                int ShiftId;
                //Checking session of permission hours 
                dsShiftid = objPermissionEventData.GetShiftID(EmpID, DateTime.Parse(strApplicationDate).Year, DateTime.Parse(strApplicationDate).Month, DateTime.Parse(strApplicationDate).Day);
                ShiftId = Convert.ToInt32(dsShiftid.Tables[0].Rows[0][0]);
                PermissionStatus = PermissionStatusonShift(strApplicationDate, ShiftId, DateTime.Parse(strFromDateTime), DateTime.Parse(strToDateTime));
                if (ds_MaxNoOfHours.Tables.Count > 0)
                {
                    if (ds_MaxNoOfHours.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToString(ds_MaxNoOfHours.Tables[0].Rows[0]["PermissionBeforeLeave"]) == "False")
                        {
                            dsLeaveDetails = objPermissionEventData.CheckPermissionBeforeAfterWithLeave(DateTime.Parse(strFromDateTime).ToShortDateString(), DateTime.Parse(strToDateTime).ToShortDateString(), "PermissionBeforeLeave", Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strApplicationDate).ToShortDateString());
                            if (dsLeaveDetails.Tables.Count > 0)
                            {
                                if (dsLeaveDetails.Tables[0].Rows.Count > 0)
                                {
                                    if (PermissionStatus == "First Half")
                                    {
                                        //No need to check
                                    }
                                    else if (PermissionStatus == "Second Half")
                                    {
                                        if (Convert.ToString(dsLeaveDetails.Tables[0].Rows[0]["Leave_SessionFrom"]) == "First half")
                                        {
                                            Message(rm.GetString("Msg_PermissionBeforeLeave", ci));
                                            //lbl_Error.Text = "Permission before leave is not applicable";
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //Check Permission After Leave
                if (ds_MaxNoOfHours.Tables.Count > 0)
                {
                    if (ds_MaxNoOfHours.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToString(ds_MaxNoOfHours.Tables[0].Rows[0]["PermissionAfterLeave"]) == "False")
                        {
                            dsLeaveDetails = objPermissionEventData.CheckPermissionBeforeAfterWithLeave(DateTime.Parse(strFromDateTime).ToShortDateString(), DateTime.Parse(strToDateTime).ToShortDateString(), "PermissionAfterLeave", Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strApplicationDate).ToShortDateString());
                            if (dsLeaveDetails.Tables.Count > 0)
                            {
                                if (dsLeaveDetails.Tables[0].Rows.Count > 0)
                                {
                                    if (PermissionStatus == "First Half")
                                    {
                                        if (Convert.ToString(dsLeaveDetails.Tables[0].Rows[0]["Leave_SessionTo"]) == "Second half")
                                        {
                                            Message(rm.GetString("Msg_PermissionAfterLeave", ci));
                                            //lbl_Error.Text = "Permission after leave is not applicable";
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        //Permission allowed
                                    }
                                }
                            }
                        }
                    }
                }
                //Check Permission and Leave on Same day
                dsLeaveDetails = objPermissionEventData.CheckPermissionBeforeAfterWithLeave(DateTime.Parse(strFromDateTime).ToShortDateString(), DateTime.Parse(strToDateTime).ToShortDateString(), "PermissionOnLeave", Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strApplicationDate).ToShortDateString());
                if (dsLeaveDetails.Tables.Count > 0)
                {
                    if (dsLeaveDetails.Tables[0].Rows.Count > 0)
                    {
                        Message(rm.GetString("Msg_AppliedAlready", ci));
                        //lbl_Error.Text = "Leave already applied for this day";
                        return;
                    }
                }
                //iPermissionType_Id = ddl_PermissionType.SelectedIndex;
                iPermissionType_Id = 1;
                strFromTime = DateTime.Parse(strFromDateTime).ToLongTimeString();
                strEndTime = DateTime.Parse(strToDateTime).ToLongTimeString();
                strReason = txtReason.Text;
                if (iModifyFlag == 0)
                {
                    string strStatus = string.Empty;
                    if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
                    {
                        strStatus = "Reply";
                    }
                    else
                    {
                        strStatus = Convert.ToString(ViewState["StatusOfPermission"]);
                    }
                    string strCCMail = txtApprovalCC.Text;
                    string strPerHours = txt_NumberOfHours.Text;
                    DataSet dsPermissionApp = new DataSet();
                    //dsPermissionApp = objPermissionEventData.EditPermissionApplication(iLeavePermission_Id, Convert.ToInt32(hdnEmployeeId.Value), iPermissionType_Id, strApplicationDate, strFromDateTime, strToDateTime, strReason, Convert.ToString(Session["EmpAutoId"]), txt_NumberOfHours.Text, strPermissionStatus);
                    dsPermissionApp = objPermissionEventData.EditPermissionApplication(iLeavePermission_Id, iPermissionType_Id, strApplicationDate, strFromDateTime, strToDateTime, strReason, Convert.ToString(Session["EmpAutoId"]), strStatus, strCCMail, strPerHours, YearSettingIDforSave);
                    if (dsPermissionApp.Tables.Count > 0)
                    {
                        if (dsPermissionApp.Tables[0].Rows.Count > 0)
                        {
                            strPermissionStatus = Convert.ToString(dsPermissionApp.Tables[0].Rows[0][0]);
                            ViewState["IntimationType"] = Convert.ToString(dsPermissionApp.Tables[0].Rows[0]["UnPlanned"]);
                        }
                    }
                    string strUpdatedReason = Convert.ToString(dsPermissionApp.Tables[0].Rows[0]["Reason"]);
                    if (dsPermissionApp.Tables[0].Rows.Count > 0)
                    {
                        if (dsPermissionApp.Tables[0].Rows[0]["Permission_Id"] != DBNull.Value && Convert.ToString(dsPermissionApp.Tables[0].Rows[0]["Permission_Id"]) != string.Empty)
                        {
                            int intPerId = Convert.ToInt16(dsPermissionApp.Tables[0].Rows[0]["Permission_Id"]);
                            intPermissionId = intPerId;
                            ds_PermissionApplication = objPermissionEventData.SelectLeavePermissionByPermissionId(intPerId);
                            ViewState["PermissionAfterModify"] = ds_PermissionApplication.Tables[0];
                        }
                        if (dsPermissionApp.Tables[0].Rows[0]["LevelId"] != DBNull.Value && Convert.ToString(dsPermissionApp.Tables[0].Rows[0]["LevelId"]) != string.Empty)
                        {
                            intLevelId = Convert.ToInt64(dsPermissionApp.Tables[0].Rows[0]["LevelId"]);
                        }
                    }
                    //check whether the duration has been changed after modify
                    if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
                    {
                        DataTable dtPermissionBeforeModify = new DataTable();
                        DataTable dtPermissionAfterModify = new DataTable();
                        dtPermissionBeforeModify = (DataTable)ViewState["PermisisonBeforeModify"];
                        dtPermissionAfterModify = (DataTable)ViewState["PermissionAfterModify"];
                        if (Convert.ToString(dtPermissionBeforeModify.Rows[0]["Permission_FromTime"]) != Convert.ToString(dtPermissionAfterModify.Rows[0]["Permission_FromTime"]))
                        {
                            ViewState["ModifyStatus"] = true;
                        }
                        if (Convert.ToString(dtPermissionBeforeModify.Rows[0]["Permission_ToTime"]) != Convert.ToString(dtPermissionAfterModify.Rows[0]["Permission_ToTime"]))
                        {
                            ViewState["ModifyStatus"] = true;
                        }
                    }
                    // update the status,remareks(only) of leave application
                    //insert into TA_Tbl_LeaveConversation
                    if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
                    {
                        objPermissionEventData.UpdatePermissionApplicationConversation(iLeavePermission_Id, "Reply", 0, strReason, Convert.ToInt32(Session["EmpAutoId"]));
                    }
                    DataTable dtSanctionView = new DataTable();
                    string strEmployeeEmailId = string.Empty;
                    string strEmailIdSanctioningAuthority = string.Empty;
                    dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(iLeavePermission_Id);
                    strEmployeeEmailId = Convert.ToString(dtSanctionView.Rows[0]["emailId"]);
                    string strPermissionDate = strApplicationDate;
                    int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                    if (strPermissionStatus == "Approved")
                    {
                        // Update Processed Data Flag
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(iEmployeeID, strPermissionDate, strPermissionDate, 0);
                    }
                    ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(iEmployeeID);
                    if (ds_EmailIdOfReportingTo.Tables.Count > 0)
                        if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                            intFirstLevelAuthorityId = int.Parse(Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"]));
                    dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(iEmployeeID);
                    if (dsEmailIdOfSanctionAuthority.Tables.Count > 0)
                        if (dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            intSecondLevelAuthorityId = int.Parse(Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"]));
                    strEmailIdSanctioningAuthority = string.Empty;
                    if (dsEmailIdOfSanctionAuthority != null)
                        if (dsEmailIdOfSanctionAuthority.Tables.Count > 0)
                            if (dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                                if (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                    if (Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != "")
                                        strEmailIdSanctioningAuthority = Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]);
                    if (ds_EmailIdOfReportingTo != null)
                        if (ds_EmailIdOfReportingTo.Tables.Count > 0)
                            if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                                if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                    if (Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != string.Empty)
                                    {
                                        strEmailIdReportingTo = Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                                        //SendMail(strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, dNumberOfHoursApplied, txt_StartTime.Text, txt_EndTime.Text, TxtPermissionDate.Text, txtReason.Text, strlevelName, strPermissionStatus);
                                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                        {
                                            SendMail(intPermissionId, intLevelId, intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, Convert.ToString(ViewState["vsEmployeeEamilId"]), dNumberOfHoursApplied, txt_StartTime.Text, txt_EndTime.Text, TxtPermissionDate.Text, strUpdatedReason, strlevelName, strStatusType);
                                        }
                                    }
                    #region SMSNotification
                    try
                    {
                        DataSet dsGateway = new DataSet();
                        DataSet dsStatus = new DataSet();
                        bool isSmsEnabled = false;
                        string destinationKey = string.Empty;
                        string MessageKey = string.Empty;
                        string ServiceUrl = string.Empty;
                        string mobileNo = string.Empty;
                        string EmployeeName = string.Empty;
                        string strTemplateName = string.Empty;
                        bool isApplyAndReceiverSame = false;
                        if (strStatus == "Pending")
                            strTemplateName = "Permission Application - Apply";
                        else if (strStatus == "Forwarded")
                            strTemplateName = "Permission Application - Forward";
                        else if (strStatus == "Approved")
                            strTemplateName = "Permission Application - Approved";
                        dsStatus = objsms.GetTemplateStauts(strTemplateName);
                        string strConvertedMessage = string.Empty;
                        if (dsStatus.Tables.Count > 0)
                        {
                            if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                            {
                                dsGateway = objsms.SelectGatewayDetails();
                                if (dsGateway.Tables.Count > 0)
                                {
                                    if (dsGateway.Tables[0].Rows.Count > 0)
                                    {
                                        ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                        destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                        MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                        isSmsEnabled = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                        if (isSmsEnabled)
                                        {
                                            if (dtSanctionView.Rows.Count > 0)
                                            {
                                                if (dtSanctionView.Rows.Count > 0)
                                                {
                                                    mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                    EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                                                }
                                            }
                                        }
                                        DataSet dsReceivers = new DataSet();
                                        dsReceivers = objsms.GetReceiversDetails(strTemplateName, EmpID, EmployeeName, txt_StartTime.Text + " To " + txt_EndTime.Text, "", Convert.ToString(dNumberOfHoursApplied));
                                        if (dsReceivers.Tables.Count > 0)
                                        {
                                            if (dsReceivers.Tables[1].Rows.Count > 0)
                                            {
                                                foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                {
                                                    if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                    {
                                                        blnCheckSMS = objsms.SendSMSNotifications
                                                        (
                                                            ServiceUrl,
                                                            destinationKey,
                                                            MessageKey,
                                                            Convert.ToString(dr["Receivers"]),
                                                            Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                            Convert.ToString(dr["Mobile_Number"]),
                                                            EmpID,
                                                            strTemplateName,
                                                            Convert.ToString(dr["SwipeCardNo"])
                                                        );
                                                        if (Convert.ToString(dr["SwipeCardNo"]) == EmpID)
                                                        {
                                                            isApplyAndReceiverSame = true;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]).Contains("{User Name}"))
                                                        {
                                                            strConvertedMessage = Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]).Replace("{User Name}", Convert.ToString(dr["Receivers"]));
                                                        }
                                                        objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), EmpID, false, Convert.ToString(strConvertedMessage), "Mobile Number is not configured in employee master");
                                                        blnCheckSMS = false;
                                                    }
                                                }
                                            }
                                        }
                                        if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                        {
                                            blnCheckSMS = objsms.SendSMSNotifications
                                                            (
                                                                ServiceUrl,
                                                                destinationKey,
                                                                MessageKey,
                                                                "",
                                                                Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                Convert.ToString(mobileNo),
                                                                EmpID,
                                                                 strTemplateName,
                                                            Convert.ToString(EmpID)
                                                            );
                                        }
                                        else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                        {
                                            if (isSmsEnabled)
                                            {
                                                objsms.InsertLogDetails(strTemplateName, Convert.ToString(EmpID), EmpID, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                blnCheckSMS = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    #endregion
                    string strScript = string.Empty;
                    if (checkEmail == true && blnCheckSMS == true)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsaved", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else if (checkEmail == false && blnCheckSMS == true)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else if (checkEmail == true && blnCheckSMS == false)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationSavedbutSMSisnottriggered", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                        strScript = strScript + "</script>";
                    }
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                    //}
                    //else
                    //{
                    //    lbl_Error.Text = "Permission has already applied for these Hours";
                    //    return;
                    // }
                }
                else
                {
                    return;
                }
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_AvailableHourscouldnotbeempty", ci) + "');", true);
            return;
        }
    }
    protected string PermissionStatusonShift(string PermissionDate, int shiftId, DateTime PermissionFromTime, DateTime PermissionToTime)
    {
        DataSet dsShiftDetails = new DataSet();
        string ShiftStartTime = string.Empty;
        string ShiftEndTime = string.Empty;
        string ShiftFirstHalfStart = string.Empty;
        string ShiftFirstHalfEnd = string.Empty;
        string ShiftSecondHalfStart = string.Empty;
        string ShiftSecondHalfEnd = string.Empty;
        string status = string.Empty;
        DateTime dtShiftFirstHalfStart = new DateTime();
        DateTime dtShiftFirstHalfEnd = new DateTime();
        DateTime dtShiftSecondHalfStart = new DateTime();
        DateTime dtShiftSecondHalfEnd = new DateTime();
        dsShiftDetails = objPermissionEventData.GetShiftTime(shiftId);
        if (dsShiftDetails.Tables.Count > 0)
        {
            if (dsShiftDetails.Tables[0].Rows.Count > 0)
            {
                if (dsShiftDetails.Tables[0].Rows[0]["shift_StartTime"] != DBNull.Value)
                {
                    ShiftStartTime = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["shift_StartTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["shift_EndTime"] != DBNull.Value)
                {
                    ShiftEndTime = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["shift_EndTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_StartTime"] != DBNull.Value)
                {
                    dtShiftFirstHalfStart = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_StartTime"]));
                    ShiftFirstHalfStart = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_StartTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"] != DBNull.Value)
                {
                    dtShiftFirstHalfEnd = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"]));
                    ShiftFirstHalfEnd = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"] != DBNull.Value)
                {
                    dtShiftSecondHalfStart = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"]));
                    ShiftSecondHalfStart = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_EndTime"] != DBNull.Value)
                {
                    dtShiftSecondHalfEnd = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_EndTime"]));
                    ShiftSecondHalfEnd = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_EndTime"]);
                }
                if (ShiftStartTime.Substring(6, 2) == "PM" && ShiftEndTime.Substring(6, 2) == "AM")
                {
                    if (ShiftFirstHalfEnd != string.Empty)
                    {
                        if (ShiftFirstHalfEnd.Substring(6, 2) == "AM")
                        {
                            dtShiftFirstHalfEnd.AddDays(1);
                        }
                    }
                    if (ShiftSecondHalfStart != string.Empty)
                    {
                        if (ShiftSecondHalfStart.Substring(6, 2) == "AM")
                        {
                            dtShiftSecondHalfStart.AddDays(1);
                        }
                    }
                    if (ShiftSecondHalfEnd != string.Empty)
                    {
                        if (ShiftSecondHalfEnd.Substring(6, 2) == "AM")
                        {
                            dtShiftSecondHalfEnd = dtShiftSecondHalfEnd.AddDays(1);
                        }
                    }
                }
            }
        }
        if ((PermissionFromTime >= dtShiftFirstHalfStart && PermissionFromTime <= dtShiftFirstHalfEnd) && (PermissionToTime >= dtShiftFirstHalfStart && PermissionToTime <= dtShiftFirstHalfEnd))
        {
            status = "First Half";
        }
        else if ((PermissionFromTime >= dtShiftSecondHalfStart && PermissionFromTime <= dtShiftSecondHalfEnd) && (PermissionToTime >= dtShiftSecondHalfStart && PermissionToTime <= dtShiftSecondHalfEnd))
        {
            status = "Second Half";
        }
        return status;
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        try
        {
            int iEmployeeID = Convert.ToInt32(hdnEmployeeId.Value);
            //Check Approval Settings for EnterPrise Edition and Demo Version
            // Demo Edition - 0
            //Standard Edition -  1
            //Profession Edition - 2
            //Enterprise Edition - 3
            //Declare Permission Status
            string strPermissionStatus = string.Empty;
            //Checking grade module is available or not and changed the id value from 110 to 228
            approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
            //if (Session["Edition"].ToString() == "0" || Session["Edition"].ToString() == "3")
            if (approvalSettingsPageExists == 1)
            {
                //Get Compnay Id of the Employeee
                int intCompanyId = base.GetCompanyId(iEmployeeID);
                //Get Approval Settings Based on Company Id
                DataSet dsApprovalSettings = new DataSet();
                ShiftEvenData objShift = new ShiftEvenData();
                dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
                if (dsApprovalSettings != null)
                {
                    if (dsApprovalSettings.Tables.Count > 0)
                    {
                        if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["PermissionSanction"]) == false)
                            {
                                strPermissionStatus = "ApprovalNotRequired";
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ApprovalSettings", ci) + "');", true);
                            //base.Message(rm.GetString("Msg_ApprovalSettings"));
                            return;
                        }
                    }
                }
            }
            else
            {
                strPermissionStatus = "ApprovalNotRequired";
            }
            if (Convert.ToString(ViewState["StatusOfPermission"]) == "Pending" || strPermissionStatus == "ApprovalNotRequired")
            {
                objPermissionEventData.Delete_PermissionApplication(iLeavePermission_Id, Convert.ToInt32(Session["EmpAutoId"]));
                //Convert Date Format to yyyy/MM/dd Format
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
                string strPermissionDate = strApplicationDate;
                //The below line commend by karthikeyan for the reprocessed data 
                if (strPermissionStatus == "ApprovalNotRequired")
                {
                    // Update Processed Data Flag
                    objLeaveApplicationEventData.UpdateProcessedDataFlag(iEmployeeID, strPermissionDate, strPermissionDate, 0);
                }
                else
                {
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        MailToReportingTo();
                    }
                }
                //objLeaveApplicationEventData.UpdateProcessedDataFlag(iEmployeeID, strPermissionDate, strPermissionDate, 0);
                Session["Prev_PermissionDetails"] = null;
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationDeleted", ci) + "');";
                strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                //Page.RegisterStartupScript("AlertPDel65507866", strScript);
            }
            else
            {
                if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
                {
                    if (Convert.ToString(Session["IndividualUsers"]) == "True")
                    {
                        ControlCreation();
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_CannotdeletethisrecordPermission", ci) + "');", true);
                        //Page.RegisterStartupScript("statusalertModifyPerDel", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "');</script>");
                        return;
                    }
                    else
                    {
                        objPermissionEventData.Delete_PermissionApplication(iLeavePermission_Id, Convert.ToInt32(Session["EmpAutoId"]));
                        //Convert Date Format to yyyy/MM/dd Format
                        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                        strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
                        string strPermissionDate = strApplicationDate;
                        if (strPermissionStatus == "ApprovalNotRequired")
                        {
                            // Update Processed Data Flag
                            objLeaveApplicationEventData.UpdateProcessedDataFlag(iEmployeeID, strPermissionDate, strPermissionDate, 0);
                        }
                        else
                        {
                            if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                            {
                                MailToReportingTo();
                            }
                        }
                        //objLeaveApplicationEventData.UpdateProcessedDataFlag(iEmployeeID, strPermissionDate, strPermissionDate, 0);
                        Session["Prev_PermissionDetails"] = null;
                        string strScript = string.Empty;
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationDeleted", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                        strScript = strScript + "</script>";
                        //Dispaly alert messsage.
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                        //Page.RegisterStartupScript("AlertPDel65507866", strScript);
                    }
                }
                else
                {
                    ControlCreation();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_CannotdeletethisrecordPermission", ci) + "');", true);
                    //Page.RegisterStartupScript("statusalertModifyPerDel", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "');</script>");
                    return;
                }
            }
        }
        catch
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_CannotdeletethisrecordPermission", ci) + "');", true);
            //Page.RegisterStartupScript("test", "<script language='Javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "'); </script>");
        }
        //Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Session["Prev_PermissionDetails"] = null;
        Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
    }
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            //Convert Date Format to MM/dd/yyyy Format
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]); // christopher added
            // strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
            //Convert Date Format to MM/dd/yyyy Format // commented by christopher
            //strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), txt_StartTime.Text, "B");
            //strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), txt_EndTime.Text, "B");
            // christopher added
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), txt_StartTime.Text, "B");
            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), txt_EndTime.Text, "B");
            DateTime dtToDate = DateTime.Parse(strToDateTime);
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }
    }
    public void CompareCurrentdate(object s, ServerValidateEventArgs e)
    {
        try
        {
            //Convert Date Format to MM/dd/yyyy Format
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strApplicationDate = objClassCommon.DateTimeConvertion((gstrDateFormat), TxtPermissionDate.Text, "D");
            DateTime dtCurrentDate = DateTime.Now;
            DateTime dtFromDate = DateTime.Parse(strApplicationDate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
    }
    public void CompareTodate(object s, ServerValidateEventArgs e)
    {
        try
        {
            //Convert Date Format to MM/dd/yyyy Format
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]); // christopher added
            // commented by christopher
            //strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), txt_EndTime.Text, "B");
            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), txt_EndTime.Text, "B");
            DateTime dtCurrentDate = DateTime.Now;
            DateTime dtFromDate = DateTime.Parse(strToDateTime);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
    }
    private void SendMail(Int64 PermissionId, Int64 LevelId, int intFirstLevelAuthorityId, int intSecondLevelAuthorityId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string EmployeeEamilId, string NoOfHoursApplied, string FromTime, string ToTime, string PermissionTime, string Reason, string levelName, string StatusType)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string ScriptType = "Permission Modify Form";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                // Get the Application Root Path
                string strApplicationPath = Convert.ToString(Request.UrlReferrer);
                int intLastIndex = strApplicationPath.LastIndexOf('/');
                strApplicationPath = strApplicationPath.Substring(0, (intLastIndex - 1));
                intLastIndex = strApplicationPath.LastIndexOf('/');
                strApplicationPath = strApplicationPath.Substring(0, (intLastIndex + 1));
                string[] strSysName;
                strSysName = strApplicationPath.Split('/');
                string strServerIP = string.Empty;
                //= GetIPAddress();
                strServerIP = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ServerIP"]);
                strApplicationPath = strApplicationPath.Replace(Convert.ToString(strSysName[2]), strServerIP);
                string Employee_Code_Id = lbl_EmployeeID.Text;
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                // As per elite partner requisition, mail should be trigger from admin id, whatever we configured in setting page.
                //25-Dec-2019 02:06 PM
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Convert.ToString(Session["loginEmailId"]));
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                mailMessage.CC.Add(new MailAddress(Convert.ToString(ViewState["vsEmployeeEamilId"])));
                //Select the Recipient for To and CC based on the Approval Authority and Status            
                string strToIds = string.Empty;
                //mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
                //strToIds = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                if (Convert.ToString(ViewState["StatusOfPermission"]) == "Pending" || Convert.ToString(ViewState["StatusOfPermission"]) == "Forwarded")
                {
                    strToIds = strEmailIdReportingTo;
                }
                if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
                {
                    if (Convert.ToString(ViewState["vwReplyToPerson"]) == "1")
                    {
                        //Reporting Person
                        strToIds = strEmailIdReportingTo;
                    }
                    if (Convert.ToString(ViewState["vwReplyToPerson"]) == "2")
                    {
                        strToIds = strEmailIdSanctionAuthority;
                        mailMessage.CC.Add(strEmailIdReportingTo);
                    }
                }
                if (strToIds != string.Empty)
                {
                    string[] strArrEmailAddressForCC;
                    strArrEmailAddressForCC = SplitCCTo(strToIds);
                    MailAddressCollection MailAddrCollectionCC = mailMessage.To;
                    for (int iLoop = 0; iLoop < strArrEmailAddressForCC.Length; iLoop++)
                    {
                        MailAddress newCC = new MailAddress(strArrEmailAddressForCC[iLoop]);
                        MailAddrCollectionCC.Add(newCC);
                    }
                }
                string strStatus = string.Empty;
                mailMessage.Subject = "Permission Application - " + lbl_PermissionApplicationDate.Text + " | " + Employee_Code_Id + " - " + lbl_EmployeeName.Text + " | " + strStatus + " - Modified";
                if (Convert.ToString(ViewState["StatusOfPermission"]) == "Pending")
                {
                    strStatus = "Pending";
                }
                else if (Convert.ToString(ViewState["StatusOfPermission"]) == "Forwarded")
                {
                    strStatus = "Forwarded";
                }
                else if (Convert.ToString(ViewState["StatusOfPermission"]) == "Resend")
                {
                    strStatus = "Reply";
                    mailMessage.Subject = "TimeCheck : " + levelName + " | " + lbl_EmployeeName.Text + " " + Employee_Code_Id + " | Permission  |" + " Reply";
                }
                //string strCcMails = txtApprovalCC.Text;
                DataSet dsCCEmailIds = new DataSet();
                bool blnMailToSecondLevel = false;
                // For Unplanned permission
                if (Convert.ToInt16(ViewState["IntimationType"]) == 1)
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ViewState["LevelId"]), Convert.ToInt16(ViewState["DesignationId"]), "U");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_UnPlanned"]) == true)
                            {
                                blnMailToSecondLevel = true;
                            }
                        }
                    }
                }
                // For planned permission
                else
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ViewState["LevelId"]), Convert.ToInt16(ViewState["DesignationId"]), "P");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_Planned"]) == true)
                            {
                                blnMailToSecondLevel = true;
                            }
                        }
                    }
                }
                //CC Mails using CC group
                if (strStatus != "Reply")
                {
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables.Count > 0)
                        {
                            if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                            {
                                foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                                {
                                    MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                                    // added by Gopinath.k for Mantis Bug no.24059 & 24098
                                    if (Convert.ToString(drCcEmailId["EmailId"]) != string.Empty)
                                    {
                                        MailAddress newCC = new MailAddress(Convert.ToString(drCcEmailId["EmailId"]));
                                        MailAddrCollectionCC.Add(newCC);
                                    }
                                }
                            }
                        }
                    }
                    if (strStatus == "Pending")
                    {
                        if (blnMailToSecondLevel == true)
                        {
                            mailMessage.CC.Add(new MailAddress(strEmailIdSanctionAuthority));
                        }
                    }
                }
                else if (strStatus == "Reply")
                {
                    if (ViewState["ModifyStatus"] != null)
                    {
                        if (Convert.ToBoolean(ViewState["ModifyStatus"]) == true)
                        {
                            if (dsCCEmailIds != null)
                            {
                                if (dsCCEmailIds.Tables.Count > 0)
                                {
                                    if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                                    {
                                        foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                                        {
                                            MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                                            // added by Gopinath.k for Mantis Bug no.24059 & 24098
                                            if (Convert.ToString(drCcEmailId["EmailId"]) != string.Empty)
                                            {
                                                MailAddress newCC = new MailAddress(Convert.ToString(drCcEmailId["EmailId"]));
                                                MailAddrCollectionCC.Add(newCC);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //check for duplicate mail Ids
                //included by sashma on 20-Oct-2010
                Hashtable htToMails = new Hashtable();
                Hashtable htCCMails = new Hashtable();
                int intToMailCount = 0;
                int intCCMailCount = 0;
                //inserts the TO mailIds in the hashtable
                foreach (MailAddress ToMail in mailMessage.To)
                {
                    if (htToMails.ContainsValue(ToMail) == false)
                    {
                        htToMails.Add(intToMailCount++, ToMail);
                    }
                }
                //inserts the CC mailIds in the hashtable
                foreach (MailAddress CCMail in mailMessage.CC)
                {
                    //check whether the mail alredy exists in CC mails.
                    if (htCCMails.ContainsValue(CCMail) == false)
                    {
                        //check whether the mail alredy exists in TO mails.
                        if (htToMails.ContainsValue(CCMail) == false)
                        {
                            htCCMails.Add(intCCMailCount++, CCMail);
                        }
                    }
                }
                mailMessage.To.Clear();
                mailMessage.CC.Clear();
                //Adds the TO mails from the hastable.
                foreach (DictionaryEntry ToMails in htToMails)
                {
                    mailMessage.To.Add(Convert.ToString(ToMails.Value));
                }
                //Adds the CC mails from the hastable.
                foreach (DictionaryEntry CCMails in htCCMails)
                {
                    mailMessage.CC.Add(Convert.ToString(CCMails.Value));
                }
                mailMessage.Body = scriptText.Replace("<<PermissionForm>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", lbl_EmployeeName.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<Department>>", levelName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", "Application Date");
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", lbl_PermissionApplicationDate.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", PermissionTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", Convert.ToString(NoOfHoursApplied));
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", FromTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", ToTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", strStatus);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);
                mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml);
                // mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?Permission_Id=" + PermissionId + "&LevelId=" + LevelId + "&ApprovalType=Permission");
                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + PermissionId + "&LevelId=" + LevelId + "&ApprovalType=Permission&Status=" + strStatus + "&From_Date=&To_Date=strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=");
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('Permission Application " + StatusType + " ,Email not sent');";
                strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("AlertPAdd9966", strScript);
                checkEmail = false;
            }
        }
        catch
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Permission Application " + StatusType + " ,Email not sent');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            Page.RegisterStartupScript("AlertPAdd9966", strScript);
            checkEmail = false;
        }
    }
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    private void SendMail(string strEmployeeEmailId, string ToMailId, string strEmailIdSanctioningAuthority, string NoOfHoursApplied, string FromTime, string ToTime, string PermissionTime, string Reason, string levelName, string StatusType)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            SmtpClient loSMTPServer = new SmtpClient();
            System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
            System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            string scriptText = "";
            DataTable dtTableScript = new DataTable();
            //string Employee_Code_Id = Session["EmployeeId"].ToString();
            string Employee_Code_Id = lbl_EmployeeID.Text;
            string ScriptType = "New Permission Form";
            //  cl.fillDT("Select * from TA_TBL_EmailScripts where ScriptType='Permission Modify Form'", dtTableScript);
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Convert.ToString(Session["loginEmailId"]));
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (ToMailId != string.Empty)
                {
                    mailMessage.To.Add(new MailAddress(ToMailId));
                }
                //if (mailMessage.From.ToString() != strEmployeeEmailId)
                //{
                if (strEmployeeEmailId != string.Empty)
                {
                    mailMessage.CC.Add(new MailAddress(strEmployeeEmailId));
                }
                //}
                if (StatusType == "deleted")
                {
                    //mailMessage.Subject = levelName + " | " + Employee_Code_Id + " - " + lbl_EmployeeName.Text + " | " + TxtPermissionDate.Text + " | " + "Permission Form Deleted";
                    mailMessage.Subject = rm.GetString("email_PermissionForm", ci) + " - " + TxtPermissionDate.Text + " | " + Employee_Code_Id + " - " + lbl_EmployeeName.Text + " | " + levelName + " - " + " Deleted";
                }
                else
                {
                    //mailMessage.Subject = levelName + " | " + Employee_Code_Id + " - " + lbl_EmployeeName.Text + " | " + TxtPermissionDate.Text + " | " + "Permission Form Modified";                
                    mailMessage.Subject = rm.GetString("email_PermissionForm", ci) + " - " + TxtPermissionDate.Text + " | " + Employee_Code_Id + " - " + lbl_EmployeeName.Text + " | " + levelName + " - " + " Modified";
                }
                mailMessage.Body = scriptText.Replace("<<PermissionForm>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", lbl_EmployeeName.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", PermissionTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", Convert.ToString(NoOfHoursApplied));
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", FromTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", ToTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);
                if (StatusType == "Forwarded" || StatusType == "Pending")
                {
                    int Permission_Id = 0;
                    Permission_Id = Convert.ToInt32(Request.QueryString["Permission_Id"]);
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + Convert.ToString(Permission_Id) + "&LevelId=" + Session["LevelId"] + "&Status=" + StatusType + "&ApprovalType=Permission");
                }
                else
                {
                    string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font></a>";
                    //string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font></a>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                Message("Email Script is missing. Script Name: New Permission Form");
                checkEmail = false;
            }
        }
        catch
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            //strScript = strScript + "alert('Permission Application " + StatusType + " ,Email not sent');";
            strScript = strScript + "alert('" + rm.GetString("Menu_Transactions_Permission", ci) + " " + StatusType + " ," + rm.GetString("Alert_Emailnotsent", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
            //Page.RegisterStartupScript("AlertPAdd9966", strScript);
            checkEmail = false;
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_EmployeeID1.Text = rm.GetString("email_EmployeeId", ci);
        lbl_EmployeeName1.Text = rm.GetString("email_EmployeeName", ci);
        lbl_NumberofHoursapplied.Text = rm.GetString("email_NumberOfHoursApplied", ci);
        lbl_PermissionApplicationDate1.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        lbl_PermissionDate.Text = rm.GetString("Permission_PermissionDate", ci);
        //lbl_PermissionType.Text = rm.GetString("Permission_PermissionType", ci);
        lbl_PermisssionTime.Text = rm.GetString("Permission_PermissionTime", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        lbl_RemainingNumberofHours.Text = rm.GetString("Permission_RemaininigNumberOfHours", ci);
        lbl_StartTime.Text = rm.GetString("AllSwipes_FromTime", ci);
        lbl_EndTime.Text = rm.GetString("AllSwipes_ToTime", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        CustomValidator2.ErrorMessage = rm.GetString("Validator_LeavePermission_StartTime", ci);
        CustomValidator3.ErrorMessage = rm.GetString("Validator_LeavePermission_EndTime", ci);
        CustomValidator1.ErrorMessage = rm.GetString("Alert_SelectvalidPermissionDate", ci);
        lbl_HeaderPermission.Text = rm.GetString("Menu_Transactions_Permission", ci);
        btn_Modify.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Delete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        //btn_CalculateHrs.Text = "&nbps;&nbps;" + rm.GetString("Calculate_Hours", ci);
        btn_CalculateHrs.Text = "";
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(23, Convert.ToInt32(Session["userGroup_Id"]), "");
        //if (ds_Checkuser.Tables[0].Rows.Count == 0)
        //  {
        //       Response.Redirect("TransactionLandingPage.aspx");
        //  }
        //else
        //  {
        //        //   
        //  }      
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["modifyPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["modifyPrv"]) != 1)
            {
                Response.Redirect("TransactionLandingPage.aspx");
            }
            if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
            {
                this.btn_Delete.Visible = true;
            }
            else
            {
                this.btn_Delete.Visible = false;
            }
        }
        else
        {
            Response.Redirect("TransactionLandingPAge.aspx");
        }
    }
    private void MailToReportingTo()
    {
        string strEmployeeEmailId = string.Empty;
        string strEmailIdSanctioningAuthority = string.Empty;
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]);
        strStatusType = "deleted";
        ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(ViewState["vEmployeeId"]));
        if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
        {
            strlevelName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["levelName"]);
            strEmployeeEmailId = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["emailId"]);
        }
        ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["vEmployeeId"]));
        dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["vEmployeeId"]));
        strEmailIdSanctioningAuthority = string.Empty;
        int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
        if (dsEmailIdOfSanctionAuthority != null)
        {
            if (dsEmailIdOfSanctionAuthority.Tables.Count > 0)
            {
                if (dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                {
                    if (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                    {
                        if (Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != "")
                        {
                            strEmailIdSanctioningAuthority = Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]);
                            intSecondLevelAuthorityId = int.Parse(Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"]));
                        }
                    }
                }
            }
        }
        if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0)
        {
            if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
            {
                if (Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != string.Empty)
                {
                    strEmailIdReportingTo = Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                    intFirstLevelAuthorityId = int.Parse(Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"]));
                    strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), Convert.ToString(ViewState["vPermissionFromTime"]), "B");
                    strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), Convert.ToString(ViewState["vPermissionToTime"]), "B");
                    dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                    SendMail(strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, dNumberOfHoursApplied, txt_StartTime.Text, txt_EndTime.Text, TxtPermissionDate.Text, Convert.ToString(ViewState["vReason"]), strlevelName, strStatusType);
                    //SendMail(intPermissionId, intLevelId, intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, Convert.ToString(ViewState["vsEmployeeEamilId"]), dNumberOfHoursApplied, txt_StartTime.Text, txt_EndTime.Text, TxtPermissionDate.Text, Convert.ToString(ViewState["vReason"]), strlevelName, strStatusType);
                }
                else
                {
                    //checkEmail = false;
                }
            }
            else
            {
                //checkEmail = false;
            }
        }
        else
        {
            //checkEmail = false;
        }
        //if (checkEmail == true)
        //{
        //    // Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
        //    string strScript = string.Empty;
        //    strScript = strScript + "<script language='javascript'>";
        //    strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsaved", ci) + "');";
        //    strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
        //    strScript = strScript + "</script>";
        //    //Dispaly alert messsage.
        //    Page.RegisterStartupScript("AlertPAdd99666", strScript);
        //}
        //else
        //{
        //    string strScript = string.Empty;
        //    strScript = strScript + "<script language='javascript'>";
        //    strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent", ci) + "');";
        //    strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
        //    strScript = strScript + "</script>";
        //    //Dispaly alert messsage.
        //    Page.RegisterStartupScript("AlertPAdd99666", strScript);
        //}
    }
    #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);
        // this.RegisterStartupScript("setScript", strScript);
    }
    #endregion
    public int ConvertHoursMinsToMinutes(string inHoursMins)
    {
        try
        {
            int intTotalMinutes = 0, intHours = 0, intMinutes = 0;
            string[] HoursMins = inHoursMins.Split(':');
            //Adding if condition for avoiding input string error 
            if (Convert.ToString(HoursMins[0]) != string.Empty)
                intHours = Int16.Parse(HoursMins[0]);
            if (Convert.ToString(HoursMins[1]) != string.Empty)
                intMinutes = Int16.Parse(HoursMins[1]);
            intTotalMinutes = (intHours * 60) + intMinutes;
            return (intTotalMinutes);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    // Function to Convert Total Minutes to hh:mm format
    public string ConvertMinutesToHoursMins(double inTotalMinutes)
    {
        string strHoursMins = "00:00";
        try
        {
            double dTotHrs = Math.Floor(inTotalMinutes / 60);
            double dTotMins = inTotalMinutes % 60;
            int iTotHrs = Convert.ToInt32(dTotHrs);
            int iTotMins = Convert.ToInt32(dTotMins);
            if (Convert.ToInt32(dTotMins) >= 60)
            {
                iTotMins = Convert.ToInt32(dTotMins) % 60;
                iTotHrs += Convert.ToInt32(dTotMins) / 60;
            }
            strHoursMins = iTotHrs.ToString("00") + ":" + iTotMins.ToString("00");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return (strHoursMins);
    }
    private void ControlCreation()
    {
        //New Data table definition
        divLeaveConversation.Controls.Clear();
        DataTable dtReplyResend = new DataTable();
        dtReplyResend.TableName = "dtReplyResend";
        DataColumn dcDate = new DataColumn("Date");
        DataColumn dcCommentsBy = new DataColumn("Comments By");
        DataColumn dcComments = new DataColumn("Comments");
        dtReplyResend.Columns.Add(dcDate);
        dtReplyResend.Columns.Add(dcCommentsBy);
        dtReplyResend.Columns.Add(dcComments);
        DataRow dRowReplyResend;
        DataSet ds_PermissionConversation = new DataSet();
        ds_PermissionConversation = objPermissionEventData.GetPermissionConversation(Convert.ToInt32(Request.QueryString["Permission_Id"]));
        //if (!IsPostBack)
        //{
        //    // getting leave conversation 
        //    ViewState["PermissionConversation"] = ds_PermissionConversation;
        //}
        if (ds_PermissionConversation != null && ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            //if (ViewState["PermissionConversation"] != null)
            //{
            //    ds_PermissionConversation =(DataSet) ViewState["PermissionConversation"];
            //}
            Table leaveConversation = new Table();
            //leaveConversation.Width = Unit.Percentage(100);
            leaveConversation.CssClass = "table das-table1";
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            leaveConversationHr.CssClass = "empheader";
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci);
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            //leaveConversationHeading1.Width = 75;
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
            {
                int rowIndex = 0;
                foreach (DataRow drLeaveConversation in ds_PermissionConversation.Tables[0].Rows)
                {
                    dRowReplyResend = dtReplyResend.NewRow();
                    TableRow trLeaveConversation = new TableRow();
                    TableCell tcLeaveConversationRepliedOn = new TableCell();
                    Label lblLeaveConversationRepliedOn = new Label();
                    tcLeaveConversationRepliedOn.BorderWidth = 1;
                    tcLeaveConversationRepliedOn.Width = 200;
                    lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                    lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Convert.ToString(Session["MDateFormat"])) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Convert.ToString(Session["MTimeFormat"]));
                    dRowReplyResend["Date"] = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Convert.ToString(Session["MDateFormat"])) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Convert.ToString(Session["MTimeFormat"]));
                    tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                    trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);
                    TableCell tcLeaveConversationCommentsBy = new TableCell();
                    Label lblLeaveConversationCommentsBy = new Label();
                    tcLeaveConversationCommentsBy.Width = 200;
                    lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                    //if (Convert.ToString(drLeaveConversation["CommentsBy"]) == "0")
                    //{
                    //    lblLeaveConversationCommentsBy.Text = lbl_EmployeeName.Text;
                    //    dRowReplyResend["Comments By"] = lbl_EmployeeName.Text;
                    //}
                    //else if (Convert.ToString(drLeaveConversation["CommentsBy"]) == "1")
                    //{
                    //    lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"]));
                    //    dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"]));
                    //}
                    //else if (Convert.ToString(drLeaveConversation["CommentsBy"]) == "2")
                    //{
                    //    lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"]));
                    //    dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"]));
                    //}
                    //else if (Convert.ToString(drLeaveConversation["CommentsBy"]) == "3")
                    //{
                    lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"]));
                    dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"]));
                    // }
                    tcLeaveConversationCommentsBy.Controls.Add(lblLeaveConversationCommentsBy);
                    trLeaveConversation.Cells.Add(tcLeaveConversationCommentsBy);
                    TableCell tcLeaveConversationComments = new TableCell();
                    Label lblLeaveConversationComments = new Label();
                    lblLeaveConversationComments.ID = "lblLeaveConversationComments" + rowIndex;
                    lblLeaveConversationComments.Text = Convert.ToString(drLeaveConversation["Comments"]);
                    dRowReplyResend["Comments"] = Convert.ToString(drLeaveConversation["Comments"]);
                    tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                    trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                    leaveConversation.Rows.Add(trLeaveConversation);
                    rowIndex += 1;
                    dtReplyResend.Rows.Add(dRowReplyResend);
                }
            }
            divLeaveConversation.Controls.Add(leaveConversation);
        }
        if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            strHtml = buildPage("Test", dtReplyResend);
        }
    }
    public string buildPage(string strPageTitle, DataTable myDT)
    {
        StringBuilder sb = new StringBuilder();
        //HTML header
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>");
        sb.Append(strPageTitle);
        sb.Append("</title>");
        sb.Append("<style type='text/css'>");
        sb.Append(".Header {color: #FFFFFF; font-family: Arial;font-size: x-small;font-weight: bold;}");
        sb.Append(".rows {font-family: Arial; font-size: x-small;background-color:#FFE3B9}");
        sb.Append(".rowsNew {font-family: Arial; font-size: x-small;background-color:#FFEED5}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table border='1' cellpadding='2' style='border-collapse: collapse' bordercolor='#666666' width='700'>");
        sb.Append("  <tr bgcolor='#003466'>");
        //Table header       
        foreach (DataColumn Col in myDT.Columns)
        {
            sb.Append("<td><span class='Header'>" + Convert.ToString(Col.ColumnName) + "</span></td>");
        }
        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intWidth = 0;
        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            intWidth = 0;
            if (intIncrement % 2 == 0)
            {
                sb.Append("  <tr>");
            }
            else
            {
                sb.Append("  <tr>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                if (intWidth == 2)
                {
                    sb.Append("<td width='250px'><font face='Arial' size='2'>" + Convert.ToString(Row[Col.ColumnName]) + "</font></td>");
                    //intWidth = 1;
                }
                else
                {
                    sb.Append("<td width='30%'><font face='Arial' size='2'>" + Convert.ToString(Row[Col.ColumnName]) + "</font></td>");
                    //intWidth = 0;
                }
                intWidth = intWidth + 1;
            }
            sb.Append("  </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</body>");
        sb.Append("</html>");
        return Convert.ToString(sb);
    }
    protected void btn_print_Click(object sender, EventArgs e)
    {
        #region Eastman
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToString(Session["packageID"]) == "155")
            {
                if (PolicyExistsEmployees.Value == string.Empty)
                {
                    AddJavascriptCode();
                    return;
                }
                if (PolicyExistsEmployees.Value == "true")
                {
                    prevDs = (DataSet)Session["Prev_PermissionDetails"];
                    GenerateEmployeeTableControls(prevDs);
                    PolicyExistsEmployees.Value = "";
                }
            }
        #endregion
    }
    private void AddJavascriptCode()
    {
        string script = " objHiddenField = document.getElementById('" + PolicyExistsEmployees.ClientID + @"'); objSubmit = document.getElementById('" + btn_print.ClientID + @"'); if(confirm('Do You want to print this application?') == true){ objHiddenField.value = 'true'; objSubmit.click();}else { objHiddenField.value = 'cancel'; objSubmit.click();}";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "confirm1", script, true);
    }
    private void GenerateEmployeeTableControls(DataSet savedds)
    {
        string scriptText = "";
        DataTable dtTableScript = new DataTable();
        dtTableScript = objLeaveApplicationEventData.GetEmailScripts("PermissionApplication_Print");
        if (dtTableScript.Rows.Count > 0)
        {
            scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
            scriptText = scriptText.Replace("<<employeeidfield>>", Convert.ToString(ViewState["vsEmpID"]));
            scriptText = scriptText.Replace("<<employeenamefield>>", Convert.ToString(ViewState["vsEmpFirstName"]) + " " + Convert.ToString(ViewState["vsEmpLastName"]));
            scriptText = scriptText.Replace("<<departmentnamefield>>", Convert.ToString(ViewState["vslevelName"]));
            DataSet ds = savedds;
            int tot = (ds.Tables[0].Rows.Count > 5) ? (ds.Tables[0].Rows.Count - 5) : 0;
            int increment = 1;
            for (int i = tot; i < ds.Tables[0].Rows.Count; i++)
            {
                string testing = "<hr id='hr" + increment + "' style='display: none;";
                string testing1 = "<hr id='hr" + increment + "' style='";
                scriptText = scriptText.Replace("<table id='table" + increment + "' style='display: none'>", "<table id='table" + increment + "'>");
                scriptText = scriptText.Replace("<hr id='hr" + increment + "' style='display: none;", "<hr id='hr" + increment + "' style='");
                scriptText = scriptText.Replace("<<date" + increment + ">>", Convert.ToString(ds.Tables[0].Rows[i]["Permission_Date"]));
                scriptText = scriptText.Replace("<<intime" + increment + ">>", Convert.ToString(ds.Tables[0].Rows[i]["Permission_ToTime"]));
                scriptText = scriptText.Replace("<<latehours" + increment + ">>", Convert.ToString(ds.Tables[0].Rows[i]["No_Of_Hours"]));
                scriptText = scriptText.Replace("<<reason" + increment + ">>", Convert.ToString(ds.Tables[0].Rows[i]["Permission_Reason"]));
                scriptText = scriptText.Replace("<<receiveddate" + increment + ">>", Convert.ToString(ds.Tables[0].Rows[i]["Permission_AppliedDate"]));
                increment += 1;
            }
            pn.Controls.Add(new LiteralControl(scriptText));
            Session["ctrl"] = pn;
            string strScript = "";
            strScript = strScript + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
            strScript = strScript + "<meta http-equiv='X-UA-Compatible' content='IE=edge' />";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "window.open('Print.aspx','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
            strScript = strScript + "</script>";
            Response.Write(strScript);
            return;
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Table script is missing,contact support team of timecheck');", true);
            return;
        }
    }
    private void GenerateEmployeeTableControlsWithoutDatabaseConnectivity(DataSet savedds, string s)
    {
        Label lblFormHeader = new Label();
        lblFormHeader.Text = "Permission Request Slip";
        lblFormHeader.Style.Add("font-size", "25px");
        Table tblEmployee = new Table();
        tblEmployee.CellPadding = 5;
        tblEmployee.CellSpacing = 0;
        tblEmployee.Width = Unit.Pixel(600);
        tblEmployee.Style.Add("border", "1px solid black");
        TableHeaderRow hr = new TableHeaderRow();
        hr.Font.Size = 10;
        TableCell thcEmployeeid = new TableCell();
        thcEmployeeid.Font.Size = 10;
        thcEmployeeid.Attributes.Add("style", "width:15%;height:10px;border:1px solid black");
        TableCell thcName = new TableCell();
        thcName.Font.Size = 10;
        thcName.Attributes.Add("style", "width:28%;height:10px;border:1px solid black");
        TableCell thcDepartment = new TableCell();
        thcDepartment.Font.Size = 10;
        thcDepartment.Attributes.Add("style", "width:28%;height:10px;border:1px solid black");
        TableCell thcDivShortForm = new TableCell();
        thcDivShortForm.Font.Size = 10;
        thcDivShortForm.Attributes.Add("style", "width:28%;height:10px;border:1px solid black");
        thcEmployeeid.Text = "Employee ID";
        thcName.Text = "Employee Name";
        thcDepartment.Text = "Department Name";
        thcDivShortForm.Text = "DivShortForm";
        hr.Cells.Add(thcEmployeeid);
        hr.Cells.Add(thcName);
        hr.Cells.Add(thcDepartment);
        hr.Cells.Add(thcDivShortForm);
        tblEmployee.Rows.Add(hr);
        TableHeaderRow hrv = new TableHeaderRow();
        hrv.Style.Add("border", "1px solid black");
        hrv.Font.Size = 10;
        TableCell thcEmployeeidValue = new TableCell();
        thcEmployeeidValue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;background-color:silver");
        thcEmployeeidValue.Font.Size = 10;
        TableCell thcNamevalue = new TableCell();
        thcNamevalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;background-color:silver");
        thcNamevalue.Font.Size = 10;
        TableCell thcDepartmentvalue = new TableCell();
        thcDepartmentvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;background-color:silver");
        thcDepartmentvalue.Font.Size = 10;
        TableCell thcDivShortFormvalue = new TableCell();
        thcDivShortFormvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;background-color:silver");
        thcDivShortFormvalue.Font.Size = 10;
        thcEmployeeidValue.Text = Convert.ToString(ViewState["vsEmpID"]);
        thcNamevalue.Text = Convert.ToString(ViewState["vsEmpFirstName"]) + " " + Convert.ToString(ViewState["vsEmpLastName"]);
        thcDepartmentvalue.Text = Convert.ToString(ViewState["vslevelName"]);
        thcDivShortFormvalue.Text = "";
        hrv.Cells.Add(thcEmployeeidValue);
        hrv.Cells.Add(thcNamevalue);
        hrv.Cells.Add(thcDepartmentvalue);
        hrv.Cells.Add(thcDivShortFormvalue);
        tblEmployee.Rows.Add(hrv);
        pn.Controls.Add(lblFormHeader);
        pn.Controls.Add(tblEmployee);
        GeneratePermissionTableControls(savedds);
    }
    private void GeneratePermissionTableControls(DataSet savedds)
    {
        DataSet ds = savedds;
        int tot = (ds.Tables[0].Rows.Count > 5) ? (ds.Tables[0].Rows.Count - 5) : 0;
        for (int i = tot; i < ds.Tables[0].Rows.Count; i++)
        {
            Table tblEmployee = new Table();
            tblEmployee.CellPadding = 5;
            tblEmployee.CellSpacing = 0;
            tblEmployee.Width = Unit.Pixel(600);
            tblEmployee.Height = Unit.Pixel(80);
            if (i == 0)
            {
                tblEmployee.Attributes.Add("style", "width: 600px;height:60px;");
            }
            else
            {
                tblEmployee.Attributes.Add("style", "margin-top:-5px;width: 600px;height:60px;");
            }
            for (int j = 1; j <= 2; j++)
            {
                TableRow hr = new TableRow();
                if (j == 1)
                {
                    TableCell thcPermissionHeader = new TableCell();
                    thcPermissionHeader.Text = Enum.GetName(typeof(permissionHeader), i + 1) + " PERMISSION";
                    thcPermissionHeader.Attributes.Add("style", "margin-left:-5px;text-decoration: underline;");
                    thcPermissionHeader.Font.Size = 10;
                    thcPermissionHeader.Font.Bold = true;
                    thcPermissionHeader.ColumnSpan = 5;
                    hr.Cells.Add(thcPermissionHeader);
                    tblEmployee.Rows.Add(hr);
                }
                else
                {
                    TableCell thcDate = new TableCell();
                    thcDate.Attributes.Add("style", "width:15%;height:10px;border:1px solid black");
                    thcDate.Font.Size = 10;
                    TableCell thcInTime = new TableCell();
                    thcInTime.Font.Size = 10;
                    thcInTime.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
                    TableCell thcLateTime = new TableCell();
                    thcLateTime.Font.Size = 10;
                    thcLateTime.Attributes.Add("style", "width:18%;height:10px;border:1px solid black");
                    TableCell thcReason = new TableCell();
                    thcReason.Font.Size = 10;
                    thcReason.Attributes.Add("style", "width:37%;height:10px;border:1px solid black");
                    TableCell thcreceived = new TableCell();
                    thcreceived.Font.Size = 10;
                    thcreceived.Attributes.Add("style", "width:20%;height:10px;border:1px solid black");
                    thcDate.Text = "DATE";
                    thcInTime.Text = "INTIME";
                    thcLateTime.Text = "LATE HOURS";
                    thcReason.Text = "REASON";
                    thcreceived.Text = "RECEIVED DATE";
                    hr.Cells.Add(thcDate);
                    hr.Cells.Add(thcInTime);
                    hr.Cells.Add(thcLateTime);
                    hr.Cells.Add(thcReason);
                    hr.Cells.Add(thcreceived);
                    tblEmployee.Rows.Add(hr);
                    TableRow hrv = new TableRow();
                    thcreceived.Font.Size = 10;
                    TableCell thcDateval = new TableCell();
                    thcDateval.Font.Size = 10;
                    thcDateval.Attributes.Add("style", "width:15%;height:10px;border:1px solid black");
                    TableCell thcInTimeval = new TableCell();
                    thcInTimeval.Font.Size = 10;
                    thcInTimeval.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
                    TableCell thcLateTimeval = new TableCell();
                    thcLateTimeval.Font.Size = 10;
                    thcLateTimeval.Attributes.Add("style", "width:18%;height:10px;border:1px solid black");
                    TableCell thcReasonval = new TableCell();
                    thcReasonval.Font.Size = 10;
                    thcReasonval.Attributes.Add("style", "width:37%;height:10px;border:1px solid black");
                    TableCell thcreceivedval = new TableCell();
                    thcreceivedval.Font.Size = 10;
                    thcreceivedval.Attributes.Add("style", "width:20%;height:10px;border:1px solid black");
                    thcDateval.Text = Convert.ToString(ds.Tables[0].Rows[i]["Permission_Date"]);
                    thcInTimeval.Text = Convert.ToString(ds.Tables[0].Rows[i]["Permission_ToTime"]);
                    thcLateTimeval.Text = Convert.ToString(ds.Tables[0].Rows[i]["No_Of_Hours"]);
                    thcReasonval.Text = Convert.ToString(ds.Tables[0].Rows[i]["Permission_Reason"]);
                    thcreceivedval.Text = Convert.ToString(ds.Tables[0].Rows[i]["Permission_AppliedDate"]);
                    hrv.Cells.Add(thcDateval);
                    hrv.Cells.Add(thcInTimeval);
                    hrv.Cells.Add(thcLateTimeval);
                    hrv.Cells.Add(thcReasonval);
                    hrv.Cells.Add(thcreceivedval);
                    tblEmployee.Rows.Add(hrv);
                }
            }
            pn.Controls.Add(tblEmployee);
            pn.Controls.Add(new LiteralControl("<hr style='width: 598px; margin-top:5px;margin-left: 0px; background-color: Gray; color: Gray; height: 2px;' />"));
        }
        GenerateSignatureTableControls();
    }
    private void GenerateSignatureTableControls()
    {
        Table tblEmployee = new Table();
        tblEmployee.Width = Unit.Pixel(600);
        tblEmployee.CellPadding = 5;
        tblEmployee.CellSpacing = 0;
        TableHeaderRow hr = new TableHeaderRow();
        hr.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        hr.Font.Size = 10;
        TableCell thcEmployeeid = new TableCell();
        thcEmployeeid.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcEmployeeid.Font.Size = 10;
        TableCell thcName = new TableCell();
        thcName.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcName.Font.Size = 10;
        TableCell thcDepartment = new TableCell();
        thcDepartment.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcDepartment.Font.Size = 10;
        TableCell thcDivShortForm = new TableCell();
        thcDivShortForm.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcDivShortForm.Font.Size = 10;
        thcEmployeeid.Text = "Employee Signature";
        thcName.Text = "HOD Signature";
        thcDepartment.Text = "IAD Signature";
        thcDivShortForm.Text = "HR Signature";
        hr.Cells.Add(thcEmployeeid);
        hr.Cells.Add(thcName);
        hr.Cells.Add(thcDepartment);
        hr.Cells.Add(thcDivShortForm);
        tblEmployee.Rows.Add(hr);
        TableHeaderRow hrv = new TableHeaderRow();
        hrv.Style.Add("border", "1px solid black");
        hrv.Height = Unit.Point(80);
        TableCell thcEmployeeidValue = new TableCell();
        thcEmployeeidValue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcEmployeeidValue.Height = Unit.Point(80);
        TableCell thcNamevalue = new TableCell();
        thcNamevalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcNamevalue.Height = Unit.Point(80);
        TableCell thcDepartmentvalue = new TableCell();
        thcDepartmentvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcDepartmentvalue.Height = Unit.Point(80);
        TableCell thcDivShortFormvalue = new TableCell();
        thcDivShortFormvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcDivShortFormvalue.Height = Unit.Point(80);
        hrv.Cells.Add(thcEmployeeidValue);
        hrv.Cells.Add(thcNamevalue);
        hrv.Cells.Add(thcDepartmentvalue);
        hrv.Cells.Add(thcDivShortFormvalue);
        tblEmployee.Rows.Add(hrv);
        pn.Controls.Add(tblEmployee);
        Session["ctrl"] = pn;
        string strScript = "";
        strScript = strScript + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
        strScript = strScript + "<meta http-equiv='X-UA-Compatible' content='IE=edge' />";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "window.open('Print.aspx','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
        strScript = strScript + "</script>";
        Response.Write(strScript);
        return;
    }
}
