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;
/****************************************************************************************************************************
* 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_LeavePermissionAdd : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    LeaveEventData objLeaveEventData = new LeaveEventData();
    cls_Common objClassCommon = new cls_Common();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    Rpt_Common rptcommon = new Rpt_Common();
    DataSet ds_LeaveType = new DataSet();
    DataSet ds_HoursAlreadyTaken = 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();
    SMSNotification objsms = new SMSNotification();
    int intPermissionId = 0;
    string strFromTime, strEndTime, strReason, MaxPermitHours, strEmailIdReportingTo, EmployeeEamilId, strEmpFirstName, strEmpLastName, Employee_Code_Id, gstrDateFormat, gstrTimeFormat, strApplicationDate, strFromDateTime, strToDateTime, strlevelName;
    DateTime currDate;
    int iEmployeeID, iPermissionType_Id, count, StartYear, EndYear;
    int iInsertFlag = 0;
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    DataSet ds_NextYear = new DataSet();
    //string strEmailIdSanctionAuthority;
    //string strType;
    //string strPermissionDate;
    //double dNoOfHoursTaken, dTotalHours, dNoOfHoursAlreadyTaken;
    bool checkEmail = true, checkPermissionHrsExist, blnCheckSMS = true;
    string dNumberOfHoursApplied, dNoOfRemainingHours, EmpID;
    string gstrYearSettingStartDate = string.Empty;
    string gstrYearSettingsEndDate = string.Empty;
    string gstrNextYearSettingStartDate = string.Empty,TimeFormat = string.Empty;
    string gstrNextYearSettingsEndDate = string.Empty;
    DataSet dsPermission = new DataSet();
    int payrollConfig = 0;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objClassCommon.menu("PermissionTransaction", "23");
        }
        payrollConfig = objClassCommon.CheckPageExistsInLicense(185);
        //get the culture info to set the language        
        string source_Language;
        TimeFormat = Convert.ToString(Session["ITimeFormat"]);
        
        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 + "Emp('" + rm.GetString("Alert_Norecordsfound", ci) + "','" + rm.GetString("Alert_Errorinretrivingdetails", ci) + "','" + rm.GetString("Select", ci) + "');";
        //Adding values for alert message for time checking for dd/MM/yyyy
        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_SelectanEmployee", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "','" + rm.GetString("Alert_FromAndEndTime", 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"]);
        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 = ds_NextYear.Tables[0].Rows[0]["FromDate"].ToString();
            gstrNextYearSettingsEndDate = ds_NextYear.Tables[0].Rows[0]["ToDate"].ToString();
            ViewState["NextYearSettings_Id"] = ds_NextYear.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            ds_NextYear.Dispose();
        }
        //btn_add.Attributes.Add("onclick", "return Validation();");
        //ddlEmployeeNames.Items.Add("-Select-");
        ListItem liSelect = new ListItem();
        liSelect.Value = "-Select-";
        liSelect.Text = rm.GetString("Select", ci);
        //ddlEmployeeNames.Items.Insert(0, liSelect);
        checkPermissionHrsExist = true;
        //GetEmployeeName();
        //currDate = Convert.ToDateTime(System.DateTime.Today.Date.ToShortDateString());
        //lbl_PermissionApplicationDate.Text = currDate.ToString(Convert.ToString(Session["MDateFormat"]));

        // **** Hariharan UTC Convertion *****//
        if (!IsPostBack && Convert.ToString(Session["IndividualUsers"]) != "True")
        {
            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                lbl_PermissionApplicationDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");

            }
            else
            {
                lbl_PermissionApplicationDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }
            //lbl_EntryDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " " + Convert.ToString(TimeFormat));
        }
        // ****************************************//

        //To add permission by Administrator
        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"]);
            if (Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["GroupName"]) == "SuperAdmin" || Convert.ToString(Session["IndividualUsers"]) != "True")
            {
                divEmployees.Visible = false;
                divAdmin.Visible = true;
                //PlaceHolder1.Visible = true;
            }
            else
            {
                divEmployees.Visible = true;
                //PlaceHolder1.Controls.Clear();
                divAdmin.Visible = false;
                hdnEmployeeId.Value = Convert.ToString(Session["EmpAutoId"]);
                GetEmployeeName();
                //CheckRemainingHours(hdnEmployeeId.Value); 
            }
        }
        else
        {
            divEmployees.Visible = true;
            //PlaceHolder1.Controls.Clear();
            divAdmin.Visible = false;
            hdnEmployeeId.Value = Convert.ToString(Session["EmpAutoId"]);
            GetEmployeeName();
            //CheckRemainingHours(hdnEmployeeId.Value);
        }
        //End of To add permission by Administrator 
        if (!IsPostBack)
        {
            if (lbl_EmployeeID.Text != "")
            {
                UTCindividualLoad();
                hdnEmployeeId.Value = Convert.ToString(lbl_EmployeeID.Text);
            
                //onblur = "return CheckDateShiftDate(this,SelectEmployee,SelectvalidPermissionDate,SelectvalidPermissionFromDateandTime, SelectvalidPermissionToDateandTime,Selectvalidyear,Permissionshouldnotbeappliedbeforedateofjoining,PermissionHoursfallsonWeeklyOffGlobalHoliday,SelectValidPermissionHours,ShiftNotAllocated,PermissionHoursdoesnotfallinsidetheshift,PermissionHoursfallwiththeshiftbreaktimes,PermissionHoursShouldNotInNegativeHours,PermissionHoursNotdefinedforthisemployee,MaxNumberofInstancespermonthExceeds)"
                Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "CheckDateShiftDate(this,SelectEmployee,SelectvalidPermissionDate,SelectvalidPermissionFromDateandTime, SelectvalidPermissionToDateandTime,Selectvalidyear,Permissionshouldnotbeappliedbeforedateofjoining,PermissionHoursfallsonWeeklyOffGlobalHoliday,SelectValidPermissionHours,ShiftNotAllocated,PermissionHoursdoesnotfallinsidetheshift,PermissionHoursfallwiththeshiftbreaktimes,PermissionHoursShouldNotInNegativeHours,PermissionHoursNotdefinedforthisemployee,MaxNumberofInstancespermonthExceeds);", true);
            }
            //if (Convert.ToString(TimeFormat) == "HH:mm")
            //{
            //    lbl_PermissionApplicationDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");

            //}
            //else
            //{
            //    lbl_PermissionApplicationDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            //}
            //lbl_EntryDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " " + Convert.ToString(TimeFormat));
        }
        if(lbl_EmployeeID.Text!="")
        {
            txt_EmployeeId.Text = Convert.ToString(lbl_EmployeeID.Text);
        }
    }

    private void UTCindividualLoad()
    {
        #region UTC Time Save
        //String EmployeeID = Convert.ToString(Session["EmpAutoID"]);
        String EmployeeID = Convert.ToString(lbl_EmployeeID.Text);
        org_levelsEventData getUtcEmployeeCheck = new org_levelsEventData();
        DataSet ds_UTC = new DataSet();
        ds_UTC = getUtcEmployeeCheck.GetUTCTimeZoneEmployeeCheck(EmployeeID);
        int Counts = ds_UTC.Tables[0].Rows.Count;
        //String UTC = Convert.ToString(Session["TimezoneId"]);
        //TimeZoneName,TimeZoneDesc,HoursToBeAdded,MinToBeAdded TimezoneId
        if (Counts != 0)
        {
            Session["TimezoneId"] = ds_UTC.Tables[0].Rows[0]["TimezoneId"].ToString();
            Session["TimeZoneName"] = ds_UTC.Tables[0].Rows[0]["TimeZoneName"].ToString();
            Session["TimeZoneDesc"] = ds_UTC.Tables[0].Rows[0]["TimeZoneDesc"].ToString();
            Session["HoursToBeAdded"] = ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"].ToString();
            Session["MinToBeAdded"] = ds_UTC.Tables[0].Rows[0]["MinToBeAdded"].ToString();

            //var dt = DateTime.UtcNow;
            //var tz = TimeZoneInfo.FindSystemTimeZoneById(Convert.ToString(Session["TimeZoneName"]) + " Standard Time");
            //var DateTimeForCountry = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

            DateTime ConvertUTCTime = new DateTime();
            int hours = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"]);
            int Minutes = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["MinToBeAdded"]);
            ConvertUTCTime = objCommon.TimezoneGetDateTime(hours, Minutes);

            ViewState["CountryGetDateTime"] = ConvertUTCTime;


            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                lbl_PermissionApplicationDate.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");

            }
            else
            {
                lbl_PermissionApplicationDate.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }

            Session["CurrentCountryDatetime"] = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm:ss tt");

            string d = Session["CurrentCountryDatetime"].ToString();
            DateTime parsedDateTime;

            if (DateTime.TryParseExact(d, "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime))
            {
                string formattedDate = parsedDateTime.ToString(Convert.ToString(Session["MDateFormat"]));
                string formattedUtcTime = parsedDateTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);
                //DateTime ddddd = DateTime.Parse(Convert.ToDateTime(formattedDate).ToShortTimeString());
                Session["CurrentCountryDatetimes"] = parsedDateTime;
                String A = Session["CurrentCountryDatetimes"].ToString();
                //dtmCurrentDateTime = parsedDateTime;
            }


        }
        else
        {
            lbl_PermissionApplicationDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm tt");
        }


        #endregion

        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "EmpName('Permission');", true);

    }
    #endregion
    #region UserDefinedFunction
    public void GetEmployeeName()
    {
        if (Session["user"] == null || Convert.ToString(Session["user"]) == string.Empty)
        {
            Response.Redirect("../Index.aspx");
        }
        else
        {
            lbl_EmployeeID.Text = Convert.ToString(Session["EmployeeCodeId"]);
            iEmployeeID = Convert.ToInt32(hdnEmployeeId.Value);
            DataSet ds_EmployeeDetails = new DataSet();
            ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(iEmployeeID);
            strEmpFirstName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
            strEmpLastName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
            Employee_Code_Id = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
            lbl_EmployeeName.Text = strEmpFirstName + " " + strEmpLastName;
        }
    }
    /// <summary>
    /// Sending mail to the Reporting to Person
    /// </summary>
    /// <param name="ToMailId"></param>
    /// <param name="NoOfHoursApplied"></param>
    /// <param name="FromTime"></param>
    /// <param name="ToTime"></param>
    /// <param name="PermissionTime"></param>
    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 strPermissionStatus)
    {
        try
        {
            // Get the Application Root Path
            MailMessage mailMessage = new MailMessage();
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string ScriptType = "New Permission Form";
            string status = "";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                GetEmployeeName();
                string strApplicationPath = Request.UrlReferrer.ToString();
                int intLastIndex = strApplicationPath.LastIndexOf('/');
                strApplicationPath = strApplicationPath.Substring(0, (intLastIndex - 1));
                intLastIndex = strApplicationPath.LastIndexOf('/');
                strApplicationPath = strApplicationPath.Substring(0, (intLastIndex + 1));
                string[] strSysName;
                strSysName = strApplicationPath.Split('/');
                string strServerIP = string.Empty;
                //= GetIPAddress();
                strServerIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
                strApplicationPath = strApplicationPath.Replace(strSysName[2].ToString(), strServerIP);
                DataSet dsCCEmailIds = new DataSet();
                bool blnMailToSecondLevel = false;
                //For plannned permission
                if (Convert.ToInt16(dsPermission.Tables[0].Rows[0]["UnPlanned"].ToString()) == 0)
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["Designation_Id"].ToString()), "P");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_Planned"].ToString()) == true)
                            {
                                blnMailToSecondLevel = true;
                            }
                        }
                    }
                }
                //For UnPlanned permission
                else
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["Designation_Id"].ToString()), "U");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_UnPlanned"].ToString()) == true)
                            {
                                blnMailToSecondLevel = true;
                            }
                        }
                    }
                }


                scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
                status = strPermissionStatus;

                if (strEmailIdReportingTo == strEmailIdSanctionAuthority)
                {
                    mailMessage.To.Add(new MailAddress(strEmailIdReportingTo));
                }
                else
                {
                    mailMessage.To.Add(new MailAddress(strEmailIdReportingTo));
                    if (blnMailToSecondLevel == true)
                    {
                        mailMessage.CC.Add(new MailAddress(strEmailIdSanctionAuthority));
                    }
                }
                mailMessage.Subject = "Permission Application - " + lbl_PermissionApplicationDate.Text + " | " + Employee_Code_Id + " - " + lbl_EmployeeName.Text + " | " + strPermissionStatus;
                // 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(ViewState["vsEmployeeEamilId"].ToString()));
                string strCcMails = txtApprovalCC.Text;
                //CC mails using CC group
                if (dsCCEmailIds != null)
                {
                    if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                        {
                            MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                            // added by Gopinath.k for Mantis Bug no.24059 & 24098
                            if (drCcEmailId["EmailId"].ToString() != string.Empty)
                            {
                                MailAddress newCC = new MailAddress(drCcEmailId["EmailId"].ToString());
                                MailAddrCollectionCC.Add(newCC);
                            }
                        }
                    }
                }
                //check for duplicate mail Ids
                //included by sashma on 20-Oct-2010
                Hashtable htToMails = new Hashtable();
                Hashtable htCCMails = new Hashtable();
                int intToMailCount = 0;
                int intCCMailCount = 0;
                //inserts the TO mailIds in the hashtable
                foreach (MailAddress ToMail in mailMessage.To)
                {
                    if (htToMails.ContainsValue(ToMail) == false)
                    {
                        htToMails.Add(intToMailCount++, ToMail);
                    }
                }
                //inserts the CC mailIds in the hashtable
                foreach (MailAddress CCMail in mailMessage.CC)
                {
                    //check whether the mail alredy exists in CC mails.
                    if (htCCMails.ContainsValue(CCMail) == false)
                    {
                        //check whether the mail alredy exists in TO mails.
                        if (htToMails.ContainsValue(CCMail) == false)
                        {
                            htCCMails.Add(intCCMailCount++, CCMail);
                        }
                    }
                }
                mailMessage.To.Clear();
                mailMessage.CC.Clear();
                //Adds the TO mails from the hastable.
                foreach (DictionaryEntry ToMails in htToMails)
                {
                    mailMessage.To.Add(ToMails.Value.ToString());
                }
                //Adds the CC mails from the hastable.
                foreach (DictionaryEntry CCMails in htCCMails)
                {
                    mailMessage.CC.Add(CCMails.Value.ToString());
                }
                mailMessage.Body = scriptText.Replace("<<PermissionForm>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                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>>", status);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);
                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?Permission_Id=" + PermissionId + "&LevelId=" + LevelId + "&ApprovalType=Permission");
                if (payrollConfig == 1)
                {
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + PermissionId + "&LevelId=" + LevelId + "&ApprovalType=Permission&Status=" + status + "&From_Date=&To_Date=strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&Angler=1");
                }
                else
                {
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + PermissionId + "&LevelId=" + LevelId + "&ApprovalType=Permission&Status=" + status + "&From_Date=&To_Date=strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=");
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent1", ci) + "');";
                strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("AlertPAdd", strScript);
                checkEmail = false;
            }
        }
        catch
        {
            //Response.Write(ex.Message);
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent1", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            Page.RegisterStartupScript("AlertPAdd", strScript);
            checkEmail = false;
        }
    }
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    //Check permission status
    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;
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_EmployeeID1.Text = lblEmpId.Text = rm.GetString("email_EmployeeId", ci);
        lbl_EmployeeName1.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_StartTime.Text = rm.GetString("AllSwipes_FromTime", ci);
        lbl_EndTime.Text = rm.GetString("AllSwipes_ToTime", 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_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);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        btn_add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        BodyContentPH_lblSelectEmployee.Text = rm.GetString("lblSelectEmployee", ci);
        btn_CalculateHrs.Text = "";
        btn_Search.Text = "";
        //btn_Search.Text =  rm.GetString("btn_Search", ci);
        //btn_CalculateHrs.Text =  rm.GetString("Calculate_Hours", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(23, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        else
        {
            //   
        }
    }
    #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>";
        //this.RegisterStartupScript("setScript", strScript);
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    #endregion
    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    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"]);
            // strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
            //Convert Date Format to MM/dd/yyyy Format
            //commented on 26_sep_08
            //strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), txt_StartTime.Text, "B");
            //strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), txt_EndTime.Text, "B");
            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
        {
            //
        }
    }
    /// <summary>
    /// Compare FromMonth With Current Month
    /// </summary>
    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;
        }
    }
    /// <summary>
    /// Compare Tomonth with Current Month
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    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"]);
            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;
        }
    }
    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>
    /// Check Remaining number of permission 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";
        //    iInsertFlag = 1;
        //    return;
        //}
        //else if (NoOfHoursApplied <= 0)
        //{
        //    lbl_Error.Text = "Select Valid Hours";
        //    iInsertFlag = 1;
        //    return;
        //}
        if (NoOfHoursApplied != string.Empty && TotNoOfRemainingHours != string.Empty)
        {
            TimeSpan dsDiff;
            double MaxPermitHours_Mins = ConvertHoursMinsToMinutes(TotNoOfRemainingHours + ":00");
            double HoursTakenInMinutes_Mins = ConvertHoursMinsToMinutes(NoOfHoursApplied);
            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);
            //dsDiff = DateTime.Parse(TotNoOfRemainingHours).Subtract(DateTime.Parse(NoOfHoursApplied));
            //dsDiff = TimeSpan.Parse(s + ":00");
            //dsDiff = DateTime.Parse(NoOfHoursApplied).Subtract(DateTime.Parse(TotNoOfRemainingHours));
            DateTime NoOfHours = DateTime.Parse(NoOfHoursApplied);
            if (diffHours_Mins < 0)
            {
                //lbl_Error.Text = "You have exceeded the Permission Hours Limit";
                //base.Message(rm.GetString("Msg_ValidHour", ci));
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ValidHour", ci) + "');", true);
                iInsertFlag = -1;
                return;
            }
            else if (NoOfHours.Hour < 0)
            {
                //lbl_Error.Text = "Select Valid Hours";
                //base.Message(rm.GetString("Msg_ValidHour", ci));
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ValidHour", ci) + "');", true);
                iInsertFlag = -1;
                return;
            }
        }
    }
    /// <summary>
    /// Check Remaining number of permission Hours
    /// </summary>
    public void CheckRemainingHours(string EmpID, DateTime permissionDate)
    {
        ds_MaxNoOfHours = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(Convert.ToInt32(EmpID));
        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";
                }
            }
            ds_HoursAlreadyTaken = objPermissionEventData.GetHoursAlreadyTaken(Convert.ToInt32(EmpID), permissionDate);
            if (Convert.ToInt32(ds_HoursAlreadyTaken.Tables[0].Rows[0]["InstancesTaken"]) >= Convert.ToInt32(ds_MaxNoOfHours.Tables[0].Rows[0]["Permission_MaxInstances_Month"]))
            {
                iInsertFlag = -1;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ExceddNoOfinstance", ci) + "');", true);
                lblRemainNoOfHours.Text = "00:00";
                return;
            }            
            string noOfHrsApplied = (hdnNoOfHours.Value == null) ? "00:00" : hdnNoOfHours.Value;

            String NoofHrs = Convert.ToString(DateTime.Parse(noOfHrsApplied.ToString()));
            //Minimum Hrs per instance
            #region MinimumHoursPerInstance
            string Perm_MinHrsInstance = Convert.ToString(ds_MaxNoOfHours.Tables[0].Rows[0]["Permission_MinHrs_Instance"]);
            if (Convert.ToString(Perm_MinHrsInstance) != "")
            {
                if (DateTime.Parse(noOfHrsApplied) < DateTime.Parse(Perm_MinHrsInstance))
                {
                    iInsertFlag = -1;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Your Minimum Number of Hours per Instance is " + Perm_MinHrsInstance + "');", true);
                    lblRemainNoOfHours.Text = "00:00";
                    return;
                }
            }
            TimeSpan tsPermission_MaxHrs_Instance = new TimeSpan();
            string Permission_MaxHrs_Instance = Convert.ToString(ds_MaxNoOfHours.Tables[0].Rows[0]["Permission_MaxHrs_Instance"]);
            if (Permission_MaxHrs_Instance != string.Empty && Permission_MaxHrs_Instance != null)
            {
                tsPermission_MaxHrs_Instance = DateTime.Parse(Permission_MaxHrs_Instance).Subtract(DateTime.Parse(noOfHrsApplied));
            }
            if (tsPermission_MaxHrs_Instance.TotalHours < 0)
            {
                iInsertFlag = -1;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_MaxNoOfHrsInstance", ci) + " " + Permission_MaxHrs_Instance + "');", true);
                lblRemainNoOfHours.Text = "00:00";
                return;
            }
            #endregion
            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;
            string s;
            s = ConvertMinutesToHoursMins(diffHours_Mins);
            int sReturn = s.LastIndexOf(':');
            string RemainHours = s;
            lblRemainNoOfHours.Text = RemainHours;
            hdnRemainNoOfHours.Value = RemainHours;
        }
        else
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_NoPermissionHoursdefinedforthisEmployee", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
            strScript = strScript + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
            checkPermissionHrsExist = false;
        }
    }
    #endregion
    #region ButtonEvents
    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
    }
    protected void btn_add_Click(object sender, EventArgs e)
    {
        if (hdnRemainNoOfHours.Value != string.Empty)
        {
            if (Page.IsValid == true)
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]);
                strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, TxtPermissionDate.Text);
                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;
                }
                if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
                {
                }
                else
                {
                    if (Convert.ToDateTime(strFromDateTime) < DateTime.Now || Convert.ToDateTime(strToDateTime) < DateTime.Now)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Permission_PastDate", ci) + "');", true);
                        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"]);
                }
                dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                // txt_NumberOfHours.Text = dNumberOfHoursApplied.ToString();
                if (iInsertFlag == -1)
                {
                    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"]);
                    EmployeeEamilId = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["EmailId"]);
                    ViewState["vsEmployeeEamilId"] = EmployeeEamilId;
                }
                else
                {
                    //lbl_Error.Text = "Select Employee";
                    //base.Message(rm.GetString("lblSelectEmployee", ci));
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("lblSelectEmployee", ci) + "');", true);
                    return;
                }
                dNoOfRemainingHours = hdnRemainNoOfHours.Value;
                //dNoOfRemainingHours = lblRemainNoOfHours.Text;
                //dTotalHours = dNoOfHoursTaken - dNumberOfHoursApplied;
                CheckRemainingHours(hdnEmployeeId.Value, DateTime.Parse(strApplicationDate));
                if (checkPermissionHrsExist == false)
                {
                    lbl_Error.Text = string.Empty;
                    return;
                }
                CheckHours(dNumberOfHoursApplied, dNoOfRemainingHours);
                //Check Permission Before Leave
                string PermissionStatus;
                DataSet dsShiftid = new DataSet();
                DataSet dsLeaveDetails = 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[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[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;
                    }
                }
                if (iInsertFlag == 0)
                {
                    //     //Check FromTime and EndTime. Check whether the Permission has already applied for a particular Date and Hour. 
                    //iEmployeeID = Convert.ToInt32(Session.Contents["EmpAutoId"]);
                    iEmployeeID = Convert.ToInt32(hdnEmployeeId.Value);
                    //iPermissionType_Id = ddl_PermissionType.SelectedIndex;
                    // strPermissionDate = DateTime.Parse(lbl_PermissionApplicationDate.Text).ToShortDateString();
                    iPermissionType_Id = 1;
                    count = objPermissionEventData.CheckPermissionHours(iEmployeeID, strApplicationDate, strFromDateTime, strToDateTime);
                    //     //Calling InsertpermissionHours Method
                    if (count == 0)
                    {
                        strFromTime = DateTime.Parse(strFromDateTime).ToLongTimeString();
                        strEndTime = DateTime.Parse(strToDateTime).ToLongTimeString();
                        strReason = txtReason.Text;
                        try
                        {
                            //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;
                            string strPermissionStatusNew = string.Empty;
                            int permissionSanctionExists = 0;
                            int approvalSettingsPageExists = 0;
                            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
                                                {
                                                    strPermissionStatusNew = objShift.GetApprovalStatus(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(hdnEmployeeId.Value), Convert.ToBoolean(Session["ReportsBasedOn"]));
                                                    if (strPermissionStatusNew != string.Empty && strPermissionStatusNew != null)
                                                    {
                                                        strPermissionStatus = strPermissionStatusNew;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //base.Message(rm.GetString("Msg_ApprovalSettings", ci));
                                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ApprovalSettings", ci) + "');", true);
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                strPermissionStatus = "Approved";
                            }
                            string strCCMail = txtApprovalCC.Text;
                            string strPerHours = txt_NumberOfHours.Text;
                            DataTable dtSanctionView = new DataTable();
                            string strEmployeeEmailId = string.Empty;
                            string strEmailIdSanctioningAuthority = string.Empty;
                            string strPerStatus = string.Empty;
                            dsPermission = objPermissionEventData.InsertPermissionHours(iEmployeeID, strApplicationDate, iPermissionType_Id, strFromDateTime, strToDateTime, strReason, Convert.ToString(Session["EmpAutoId"]), Convert.ToString(ViewState["YearSettings_Id"]), strPermissionStatus, strCCMail, Convert.ToString(dNumberOfHoursApplied));
                            Int64 intLevelId = 0;
                            int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                            if (dsPermission.Tables[0].Rows.Count > 0)
                            {
                                if (dsPermission.Tables[0].Rows[0]["Permission_Id"] != DBNull.Value && Convert.ToString(dsPermission.Tables[0].Rows[0]["Permission_Id"]) != string.Empty)
                                {
                                    intPermissionId = Convert.ToInt32(dsPermission.Tables[0].Rows[0]["Permission_Id"]);
                                }
                                if (dsPermission.Tables[0].Rows[0]["LevelId"] != DBNull.Value && Convert.ToString(dsPermission.Tables[0].Rows[0]["LevelId"]) != string.Empty)
                                {
                                    intLevelId = Convert.ToInt64(dsPermission.Tables[0].Rows[0]["LevelId"]);
                                }
                                if (dsPermission.Tables[0].Rows[0]["Status"] != DBNull.Value && Convert.ToString(dsPermission.Tables[0].Rows[0]["Status"]) != string.Empty)
                                {
                                    strPerStatus = Convert.ToString(dsPermission.Tables[0].Rows[0]["Status"]);
                                }
                            }
                            dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(intPermissionId);
                            strEmployeeEmailId = Convert.ToString(dtSanctionView.Rows[0]["emailId"]);
                            string strPermissionDate = strApplicationDate;
                            if (strPermissionStatus == "Approved")
                            {
                                // Update Processed Data Flag
                                objLeaveApplicationEventData.UpdateProcessedDataFlag(iEmployeeID, strPermissionDate, strPermissionDate, 0);
                            }
                            ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(iEmployeeID);
                            dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(iEmployeeID);
                            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"]);
                                                intSecondLevelAuthorityId = int.Parse(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                                            }
                                        }
                                    }
                                }
                            }
                            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"]) != "")
                                            {
                                                strEmailIdReportingTo = Convert.ToString(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                                                intFirstLevelAuthorityId = int.Parse(ds_EmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                                                //SendMail(intPermissionId, strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, dNumberOfHoursApplied, txt_StartTime.Text, txt_EndTime.Text, TxtPermissionDate.Text, strReason, strlevelName, strPerStatus);
                                                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                                {
                                                    SendMail(intPermissionId, intLevelId, intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, EmployeeEamilId, dNumberOfHoursApplied, txt_StartTime.Text, txt_EndTime.Text, TxtPermissionDate.Text, strReason, strlevelName, strPerStatus);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            #region SMSNotification
                            try
                            {
                                int smsIsRequired = 0;
                                //To check SMS Template is available in page table or not. if no then it will skip the SMS Triggering portion.
                                //244 is template page id
                                smsIsRequired = objClassCommon.CheckPageExistsInLicense(244);
                                if (smsIsRequired > 0)
                                {
                                    DataSet dsGateway = new DataSet();
                                    DataSet dsStatus = new DataSet();
                                    bool isSmsEnabledForEmployee = 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 (strPerStatus == "Pending")
                                    {
                                        strTemplateName = "Permission Application - Apply";
                                    }
                                    else if (strPerStatus == "Forwarded")
                                    {
                                        strTemplateName = "Permission Application - Forward";
                                    }
                                    else if (strPerStatus == "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)
                                                {
                                                    if (dsGateway.Tables[0].Rows[0]["ServiceUrl"] != null)
                                                    {
                                                        ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                                    }
                                                    if (dsGateway.Tables[0].Rows[0]["DestinationKey"] != null)
                                                    {
                                                        destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                                    }
                                                    if (dsGateway.Tables[0].Rows[0]["MessageKey"] != null)
                                                    {
                                                        MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                                    }
                                                    if (dsStatus.Tables[0].Rows[0]["ToEmployee"] != null)
                                                    {
                                                        isSmsEnabledForEmployee = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                                    }
                                                    if (isSmsEnabledForEmployee)
                                                    {
                                                        if (dtSanctionView.Rows.Count > 0)
                                                        {
                                                            if (dtSanctionView.Rows[0]["Mobile_Number"] != null)
                                                            {
                                                                mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                            }
                                                        }
                                                    }
                                                    if (dtSanctionView.Rows.Count > 0)
                                                    {
                                                        if (dtSanctionView.Rows[0]["Employee_FirstName"] != null)
                                                        {
                                                            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 (dsReceivers.Tables[0].Rows[0]["Message"] != null)
                                                                    {
                                                                        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,
                                                                            EmployeeName,
                                                                            Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                            Convert.ToString(mobileNo),
                                                                            EmpID,
                                                                             strTemplateName,
                                                                        Convert.ToString(EmpID)

                                                                        );

                                                    }
                                                    else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                    {
                                                        if (isSmsEnabledForEmployee)
                                                        {
                                                            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;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    blnCheckSMS = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            #endregion
                        }
                        catch
                        {
                            checkEmail = false;
                        }
                        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 this Day";
                        //base.Message(rm.GetString("Msg_permissionAppliedforDay", ci));
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_permissionAppliedforDay", ci) + "');", true);
                        // ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", alert(" + rm.GetString("Msg_permissionAppliedforDay",ci)) , false);
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                lblRemainNoOfHours.Text = hdnRemainNoOfHours.Value;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_AvailableHourscouldnotbeempty", ci) + "');", true);
            return;
        }
    }
    public int ConvertHoursMinsToMinutes(string inHoursMins)
    {
        try
        {
            int intTotalMinutes = 0, intHours = 0, intMinutes = 0;
            string[] HoursMins = inHoursMins.Split(':');
            intHours = Int16.Parse(HoursMins[0]);
            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);
    }
    #endregion

/****************************************************************************************************************************
* Project Name    : TimeCheck                  Started Date  : 12-Jan-2024
* Module          : Permission                 Last Modified : 27-May-2011
* Programmer      : Hariharan.J
* Modified by     : Hariharan.J
*****************************************************************************************************************************/
    protected void txt_EmployeeId_TextChanged(object sender, EventArgs e)
    {
        #region UTC Time Save
        //String EmployeeID = Convert.ToString(Session["EmpAutoID"]);
        String EmployeeID = Convert.ToString(txt_EmployeeId.Text);
        org_levelsEventData getUtcEmployeeCheck = new org_levelsEventData();
        DataSet ds_UTC = new DataSet();
        ds_UTC = getUtcEmployeeCheck.GetUTCTimeZoneEmployeeCheck(EmployeeID);
        int Counts = ds_UTC.Tables[0].Rows.Count;
        //String UTC = Convert.ToString(Session["TimezoneId"]);
        //TimeZoneName,TimeZoneDesc,HoursToBeAdded,MinToBeAdded TimezoneId
        if (Counts != 0)
        {
            Session["TimezoneId"] = ds_UTC.Tables[0].Rows[0]["TimezoneId"].ToString();
            Session["TimeZoneName"] = ds_UTC.Tables[0].Rows[0]["TimeZoneName"].ToString();
            Session["TimeZoneDesc"] = ds_UTC.Tables[0].Rows[0]["TimeZoneDesc"].ToString();
            Session["HoursToBeAdded"] = ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"].ToString();
            Session["MinToBeAdded"] = ds_UTC.Tables[0].Rows[0]["MinToBeAdded"].ToString();


            DateTime ConvertUTCTime = new DateTime();
            int hours = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"]);
            int Minutes = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["MinToBeAdded"]);
            ConvertUTCTime = objCommon.TimezoneGetDateTime(hours, Minutes);

            ViewState["CountryGetDateTime"] = ConvertUTCTime;


            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                lbl_PermissionApplicationDate.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");

            }
            else
            {
                lbl_PermissionApplicationDate.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }

            Session["CurrentCountryDatetime"] = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm:ss tt");

            string d = Session["CurrentCountryDatetime"].ToString();
            DateTime parsedDateTime;

            if (DateTime.TryParseExact(d, "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime))
            {
                string formattedDate = parsedDateTime.ToString(Convert.ToString(Session["MDateFormat"]));
                string formattedUtcTime = parsedDateTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);
                //DateTime ddddd = DateTime.Parse(Convert.ToDateTime(formattedDate).ToShortTimeString());
                Session["CurrentCountryDatetimes"] = parsedDateTime;
                String A = Session["CurrentCountryDatetimes"].ToString();
                //dtmCurrentDateTime = parsedDateTime;
            }


        }
        else
        {
            lbl_PermissionApplicationDate.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm tt");
        }


        #endregion

        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "EmpName('Permission');", true);

    }
}
