using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Configuration;
using System.Text;

public partial class Masters_TA_UI_TimeSheetEntry : Base.BasePage
{
    #region VariableDeclaration
    cls_master_levels class1 = new cls_master_levels();
    DataSet dsProject = new DataSet();
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objcommon = new cls_Common();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    string source_Language;
    TimeSheetEntry objTimeSheet = new TimeSheetEntry();
    EmployeeEventData objEmployee = new EmployeeEventData();
    ProjectEventData objproject = new ProjectEventData();
    DataSet dsprojects = new DataSet();
    string strScript = string.Empty;
    int total = 0;
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    LeaveEventData leaveTypeData = new LeaveEventData();
    int workFromHomeLeaveTypeID = 0;
    #endregion
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        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"]);
        //gvTaskEntry.CssClass = Convert.ToString(Session["GridCSS"]);
        if (!IsPostBack)
        {
            txtShiftDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
            objcommon.menu("ManualTransaction", "285");
            LoadStrings(ci);
            UserRights();
            getLeaveTypeDetails();
            BindCurrentDateTimeSheetEntries();
        }
        string TimeFormat = string.Empty;
        TimeFormat = Convert.ToString(Session["ITimeFormat"]);
        if (TimeFormat == "HH:mm")
        {
            hiddenTime.Value = "HH:mm";
        }
        else
        {
            hiddenTime.Value = "LT";
        }
        hdnShiftDateFormat.Value = Convert.ToString(Session["IDateFormat"]);
        Page.MaintainScrollPositionOnPostBack = true;
    }
    private void LoadStrings(CultureInfo ci)
    {
    }
    private void UserRights()
    {
        if (ViewState["vs_ds_Checkuser"] == null)
        {
            ds_Checkuser = objCheckUser.checkRights(285, Convert.ToInt32(Session["userGroup_Id"]), "");
            ViewState["vs_ds_Checkuser"] = ds_Checkuser;
        }
        else
            ds_Checkuser = (DataSet)ViewState["vs_ds_Checkuser"];
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
            {
            }
            else
            {
                Response.Redirect("MasterLandingPage.aspx");
            }
        }
        else
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
    protected void BindCurrentDateTimeSheetEntries()
    {
        DataTable dtCurrentdayTask = new DataTable();
        dtCurrentdayTask = objTimeSheet.GetCurrentDateProgressDetails(Convert.ToString(txtShiftDate.Text), Convert.ToInt64(Session["EmpAutoID"]));
        if (dtCurrentdayTask.Rows.Count > 0)
        {
            gvTaskEntry.DataSource = dtCurrentdayTask;
            gvTaskEntry.DataBind();
        }
        else
        {
            dtCurrentdayTask.Rows.Add(dtCurrentdayTask.NewRow());
            gvTaskEntry.DataSource = dtCurrentdayTask;
            gvTaskEntry.DataBind();
            gvTaskEntry.Rows[0].Visible = false;
        }
        ViewState["dtCurrentdayTask"] = dtCurrentdayTask;
    }

    protected void gvTaskEntry_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("ADD"))
        {
            string gstrDateFormat = string.Empty;
            string shiftDate = string.Empty;
            string timesheetStatus = "Pending";
            getLeaveTypeDetails();
            if (workFromHomeLeaveTypeID == 0)
            {
                strScript = "alert('You are not eligible to enter Timesheet entry');";
                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                return;
            }
            else if (Session["EmployeeId"] != null && Convert.ToString(Session["EmployeeId"]) != "admin")
            {
                if (txtShiftDate.Text == string.Empty)
                {
                    strScript = "alert('Select Timesheet Entry Date before adding');";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                    return;
                }
                else if (txtShiftDate.Text != string.Empty)
                {
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    shiftDate = objcommon.DateTimeConvertion((gstrDateFormat), txtShiftDate.Text, "D");
                    DateTime dtCurrentDate = DateTime.Now;
                    DateTime dtToDate = DateTime.Parse(shiftDate);
                    TimeSpan diff = dtToDate.Subtract(dtCurrentDate);
                    int day = diff.Days;
                    if (day > 0)
                    {
                        strScript = "alert('Timesheet entry should not be allowed to enter for future date');";
                        ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                        return;
                    }
                    else if (day < -560)
                    {
                        strScript = "alert('Timesheet entry should not be allowed to enter for very past date');";
                        ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                        return;
                    }
                }
                int fullDayCount = 0;
                int halfDayCount = 0;
                fullDayCount = objLeaveApplicationEventData.CheckLeaveApplication(Convert.ToInt32(Session["EmpAutoID"]), shiftDate, shiftDate, Convert.ToInt32(workFromHomeLeaveTypeID));
                halfDayCount = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(Session["EmpAutoID"]), shiftDate, shiftDate, "First Half", "Second Half");
                if (fullDayCount != 0 || halfDayCount != 0)
                {

                    DataSet dsCheck = new DataSet();
                    dsCheck = objTimeSheet.validateTimeSheetAlreadyAvailable(shiftDate, Convert.ToInt64(Session["EmpAutoID"]));
                    if (dsCheck.Tables.Count > 0)
                    {
                        if (dsCheck.Tables[0].Rows.Count > 0)
                        {
                            strScript = "alert('Timesheet entry is already entered for this date');";
                            ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                            return;
                        }
                    }
                    {
                        DropDownList ddlProjectName = (DropDownList)gvTaskEntry.FooterRow.FindControl("ddlProjectNameAdd");
                        DropDownList ddlTaskList = (DropDownList)gvTaskEntry.FooterRow.FindControl("ddlTaskListAdd");
                        Label lbldefinedHours = (Label)gvTaskEntry.FooterRow.FindControl("lbldefinedHoursAdd");
                        TextBox txtadd_TaskDesc = (TextBox)gvTaskEntry.FooterRow.FindControl("txtadd_TaskDesc");
                        TextBox txtaddSpentHours = (TextBox)gvTaskEntry.FooterRow.FindControl("txtaddSpentHours");
                        string strScript = "";
                        if (ddlProjectName != null && ddlTaskList != null && lbldefinedHours != null && txtadd_TaskDesc != null && txtaddSpentHours != null)
                        {
                            if (ddlProjectName.SelectedItem.Value == "0" || ddlProjectName.SelectedItem.Value == "-Select-")
                            {
                                strScript = "alert('Please select project name before saving');";
                                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                                return;
                            }
                            else if (ddlTaskList.SelectedItem.Value == "0")
                            {
                                strScript = "alert('Please select task name in task list before saving');";
                                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                                return;
                            }
                            else if (Convert.ToString(txtadd_TaskDesc.Text) == "")
                            {
                                strScript = "alert('Enter task description before saving');";
                                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                                return;
                            }
                            else if (Convert.ToString(txtaddSpentHours.Text) == "")
                            {
                                strScript = "alert('Enter task spent hours,before Saving');";
                                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                                return;
                            }
                            else
                            {
                                timesheetStatus = GetStatusBasedOnAllocation(Convert.ToString(Session["EmployeeCodeId"]));
                                objTimeSheet.InsertTimesheetEntry
                                (
                                    Convert.ToInt64(ddlTaskList.SelectedItem.Value),
                                    Convert.ToInt64(ddlProjectName.SelectedItem.Value),
                                    Convert.ToString(lbldefinedHours.Text),
                                    Convert.ToString(txtadd_TaskDesc.Text),
                                    Convert.ToString(txtaddSpentHours.Text),
                                    Convert.ToInt64(Session["EmpAutoID"]),
                                    timesheetStatus,
                                    Convert.ToString(txtShiftDate.Text),
                                    "I"
                                );
                            }
                        }
                        BindCurrentDateTimeSheetEntries();
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Unable to find Work from home requisition in leave application for selected date or your requisition is not approved by your supervisor,please get the approval first');", true);
                    return;
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Timesheet entry should be allowed in employees login alone');", true);
                return;
            }
        }
    }

    protected void gvTaskEntry_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblTaskDetailID = (Label)gvTaskEntry.Rows[e.RowIndex].FindControl("lblProjectTaskID");
        if (lblTaskDetailID != null)
        {
            objTimeSheet.DeleteProgressTaskDetails(Convert.ToInt32(lblTaskDetailID.Text));
        }
        BindCurrentDateTimeSheetEntries();
    }

    protected void gvTaskEntry_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList ddlProjectName = (DropDownList)gvTaskEntry.Rows[e.RowIndex].FindControl("ddlProjectNameEdit");
        DropDownList ddlTaskName = (DropDownList)gvTaskEntry.Rows[e.RowIndex].FindControl("ddlTaskListEdit");
        Label lblDefinedHours = (Label)gvTaskEntry.Rows[e.RowIndex].FindControl("lbldefinedHoursEdit");
        TextBox txtTaskDescription = (TextBox)gvTaskEntry.Rows[e.RowIndex].FindControl("txtedit_TaskDesc");
        TextBox txtTaskSpentHours = (TextBox)gvTaskEntry.Rows[e.RowIndex].FindControl("txtEditSpentHours");
        Label lblTaskID = (Label)gvTaskEntry.Rows[e.RowIndex].FindControl("lblTaskID");
        string strScript = "<script language='javascript' type='text/javascript'>";
        string timesheetStatus = "Pending";
        if (lblTaskID != null && ddlProjectName != null && ddlTaskName != null && lblDefinedHours != null && txtTaskDescription != null && txtTaskSpentHours != null)
        {
            if (ddlProjectName.SelectedItem.Value == "0")
            {
                strScript = "alert('Please Project Name before saving');";
                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                return;
            }
            else if (ddlTaskName.SelectedItem.Value == "0")
            {
                strScript = "alert('Please select Task name before saving');";
                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                return;
            }
            else
            {
                timesheetStatus = GetStatusBasedOnAllocation(Convert.ToString(Session["EmployeeCodeId"]));
                objTimeSheet.InsertTimesheetEntry
                (
                Convert.ToInt64(ddlTaskName.SelectedItem.Value),
                    Convert.ToInt64(ddlProjectName.SelectedItem.Value),
                    Convert.ToString(lblDefinedHours.Text),
                    Convert.ToString(txtTaskDescription.Text),
                    Convert.ToString(txtTaskSpentHours.Text),
                    Convert.ToInt64(Session["EmpAutoID"]),
                    timesheetStatus,
                    Convert.ToString(txtShiftDate.Text),
                    "U"
                    );
            }
        }
        gvTaskEntry.EditIndex = -1;
        BindCurrentDateTimeSheetEntries();
    }

    protected void gvTaskEntry_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (ViewState["vs_ds_Checkuser"] == null)
        {
            ds_Checkuser = objCheckUser.checkRights(280, Convert.ToInt32(Session["userGroup_Id"]), "");
            ViewState["vs_ds_Checkuser"] = ds_Checkuser;
        }
        if (ds_Checkuser.Tables.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows.Count > 0)
            {
                LinkButton lbtnAdd = (LinkButton)e.Row.FindControl("lbtnAdd");
                LinkButton imgbtnEdit = (LinkButton)e.Row.FindControl("imgbtnEdit");
                LinkButton imgbtnDelete = (LinkButton)e.Row.FindControl("imgbtnDelete");
                Label lblbackslash = (Label)e.Row.FindControl("lblbackslash");
                Label lblbackslash1 = (Label)e.Row.FindControl("lblbackslash1");
                if (lbtnAdd != null)
                    if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
                    {

                        lbtnAdd.Visible = true;
                    }
                    else
                    {
                        lbtnAdd.Visible = false;
                    }
                if (imgbtnDelete != null)
                    if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
                    {
                        imgbtnDelete.Visible = true;
                    }
                    else
                    {
                        imgbtnDelete.Visible = false;
                    }
                if (imgbtnEdit != null)
                    if (ds_Checkuser.Tables[0].Rows[0]["modifyPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["modifyPrv"]) == 1)
                    {
                        imgbtnEdit.Visible = true;
                    }
                    else
                    {
                        imgbtnEdit.Visible = false;
                    }
            }
        }
        if (e.Row.RowType == DataControlRowType.DataRow && gvTaskEntry.EditIndex == e.Row.RowIndex)
        {
            DropDownList ddlProjectNameEdit = (DropDownList)e.Row.FindControl("ddlProjectNameEdit");
            DropDownList ddlTaskListEdit = (DropDownList)e.Row.FindControl("ddlTaskListEdit");
            Label definedHrsEdit = (Label)e.Row.FindControl("lbldefinedHoursEdit");
            TextBox txtTaskDesc = (TextBox)e.Row.FindControl("txtedit_TaskDesc");
            TextBox txtEditSpentHours = (TextBox)e.Row.FindControl("txtEditSpentHours");
            #region MyRegion
            if (ddlProjectNameEdit != null && ddlTaskListEdit != null && definedHrsEdit != null && txtTaskDesc != null && txtEditSpentHours != null && txtEditSpentHours != null)
            {
                string projectNameEdit = DataBinder.Eval(e.Row.DataItem, "ProjectID").ToString();
                string taskListEdit = DataBinder.Eval(e.Row.DataItem, "TaskID").ToString();
                string definedHoursEdit = DataBinder.Eval(e.Row.DataItem, "TaskHours").ToString();
                string editTaskDesc = DataBinder.Eval(e.Row.DataItem, "TaskDescription").ToString();
                string editSpentHours = DataBinder.Eval(e.Row.DataItem, "SpentHours").ToString();

                if (projectNameEdit == "") projectNameEdit = "0";
                if (definedHoursEdit == "") definedHoursEdit = "0";
                if (editTaskDesc == "") editTaskDesc = "0";
                if (editSpentHours == "") editSpentHours = "0";
                GetProjectDetails();
                if (dsprojects.Tables.Count > 0)
                {
                    if (dsprojects.Tables[0].Rows.Count > 0)
                    {
                        if (ddlProjectNameEdit != null)
                        {
                            ddlProjectNameEdit.Items.Clear();
                            ddlProjectNameEdit.DataSource = dsprojects;
                            ddlProjectNameEdit.DataTextField = "Project_Name";
                            ddlProjectNameEdit.DataValueField = "Project_Id";
                            ddlProjectNameEdit.DataBind();
                            ddlProjectNameEdit.Items.Insert(0, new ListItem("--Select--", "0"));
                            ddlProjectNameEdit.Items.FindByValue(projectNameEdit).Selected = true;
                            if (projectNameEdit != "0")
                            {
                                if (ddlTaskListEdit != null)
                                {
                                    DataSet dsTasks = new DataSet();
                                    dsTasks = objTimeSheet.GetTaskDetailsUsingProject_Task(Convert.ToInt64(ddlProjectNameEdit.SelectedItem.Value), 0);
                                    if (dsTasks.Tables.Count > 0)
                                    {
                                        if (dsTasks.Tables[0].Rows.Count > 0)
                                        {
                                            ddlTaskListEdit.Items.Clear();
                                            ddlTaskListEdit.DataSource = dsTasks;
                                            ddlTaskListEdit.DataTextField = "TaskName";
                                            ddlTaskListEdit.DataValueField = "TaskID";
                                            ddlTaskListEdit.DataBind();
                                        }
                                        ddlTaskListEdit.Items.Insert(0, new ListItem("--Select--", "0"));
                                        ddlTaskListEdit.Items.FindByValue(taskListEdit).Selected = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (txtEditSpentHours != null)
                {
                    txtEditSpentHours.Attributes.Add("onmouseover", "javascript:return DynamicDatePickerForTime('','" + txtEditSpentHours.ClientID + "')");
                }
            }
            #endregion
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddlProjectName = (DropDownList)e.Row.FindControl("ddlProjectNameAdd");
            if (ddlProjectName != null)
            {
                GetProjectDetails();
                ddlProjectName.DataSource = dsprojects;
                ddlProjectName.DataTextField = "Project_Name";
                ddlProjectName.DataValueField = "Project_Id";
                ddlProjectName.DataBind();
                ddlProjectName.Items.Insert(0, "-Select-");
            }
            TextBox txtspentHrs = (TextBox)e.Row.FindControl("txtaddSpentHours");
            if (txtspentHrs != null)
            {
                txtspentHrs.Attributes.Add("onmouseover", "javascript:return DynamicDatePickerForTime('','" + txtspentHrs.ClientID + "')");
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowType != DataControlRowType.Footer)
        {
            if (DataBinder.Eval(e.Row.DataItem, "SpentMinuts") != null && Convert.ToString(DataBinder.Eval(e.Row.DataItem, "SpentMinuts")) != "")
            {
                total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SpentMinuts"));
                ViewState["totalMinutes"] = total;
            }
        }
    }

    private void GetProjectDetails()
    {
        dsprojects = objproject.FillProjectFilter();

        if (Session["dsprojects"] != null)
        {
            dsprojects = (DataSet)Session["dsprojects"];
        }
        else
        {
            dsprojects = objproject.FillProjectFilter();
            Session["dsprojects"] = dsprojects;
        }
    }

    protected void gvTaskEntry_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvTaskEntry.EditIndex = -1;
        BindCurrentDateTimeSheetEntries();
    }

    protected void gvTaskEntry_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvTaskEntry.EditIndex = e.NewEditIndex;
        BindCurrentDateTimeSheetEntries();
    }
    protected void ddlProjectNameAdd_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlproject = (DropDownList)sender;
        GridViewRow row = (GridViewRow)ddlproject.NamingContainer;
        if (ddlproject != null)
        {
            DropDownList ddlTasklist = (DropDownList)row.FindControl("ddlTaskListAdd");
            Label lblTaskHours = (Label)row.FindControl("lbldefinedHoursAdd");
            if (Convert.ToInt64(ddlproject.SelectedIndex) != 0)
            {
                if (ddlTasklist != null)
                {
                    DataSet dsTasks = new DataSet();
                    dsTasks = objTimeSheet.GetTaskDetailsUsingProject_Task(Convert.ToInt64(ddlproject.SelectedItem.Value), 0);
                    if (dsTasks.Tables.Count > 0)
                    {
                        if (dsTasks.Tables[0].Rows.Count > 0)
                        {
                            ddlTasklist.Items.Clear();
                            ddlTasklist.DataSource = dsTasks;
                            ddlTasklist.DataTextField = "TaskName";
                            ddlTasklist.DataValueField = "TaskID";
                            ddlTasklist.DataBind();
                        }
                    }
                }
                if (lblTaskHours != null)
                {
                    lblTaskHours.Text = "";
                }
            }
            else
            {
                if (ddlTasklist != null)
                {
                    ddlTasklist.Items.Clear();
                }
                if (lblTaskHours != null)
                {
                    lblTaskHours.Text = "";
                }
            }
            ddlTasklist.Items.Insert(0, "-Select-");
        }
    }

    protected void ddlTaskListAdd_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlTask = (DropDownList)sender;
        GridViewRow row = (GridViewRow)ddlTask.NamingContainer;
        if (ddlTask != null)
        {
            Label lblTaskHours = (Label)row.FindControl("lbldefinedHoursAdd");
            if (Convert.ToInt64(ddlTask.SelectedIndex) != 0)
            {
                DropDownList ddlprojectName = (DropDownList)row.FindControl("ddlProjectNameAdd");
                if (lblTaskHours != null && ddlprojectName != null)
                {
                    DataSet dsTasks = new DataSet();
                    if (ddlTask.SelectedItem.Value != "-Select-" && ddlprojectName.SelectedItem.Value != "-Select-")
                    {
                        dsTasks = objTimeSheet.GetTaskDetailsUsingProject_Task(Convert.ToInt64(ddlprojectName.SelectedItem.Value), Convert.ToInt16(ddlTask.SelectedItem.Value));
                        if (dsTasks.Tables.Count > 0)
                        {
                            if (dsTasks.Tables[0].Rows.Count > 0)
                            {
                                lblTaskHours.Text = dsTasks.Tables[0].Rows[0]["TaskHours"].ToString();
                            }
                            else
                            {
                                lblTaskHours.Text = "00:00";
                            }
                        }
                        else
                        {
                            lblTaskHours.Text = "00:00";
                        }
                    }
                    else
                    {
                        lblTaskHours.Text = "00:00";
                    }
                }
                else
                {
                    strScript = "alert('Not able to find the defined hours, please contact task holder!');";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                    return;
                }
            }
            else
            {
                lblTaskHours.Text = "";
            }
        }
    }

    protected void btn_add_Click(object sender, EventArgs e)
    {
        getLeaveTypeDetails();
        if (workFromHomeLeaveTypeID == 0)
        {
            strScript = "alert('You are not eligible to enter Timesheet entry');";
            ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
            return;
        }
        else if (Session["EmployeeId"] != null && Convert.ToString(Session["EmployeeId"]) != "admin")
        {
            string dateFormat = string.Empty;
            string shiftDate = string.Empty;
            if (txtShiftDate.Text == string.Empty)
            {
                strScript = "alert('Select Timesheet Entry Date before adding');";
                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                return;
            }
            else if (txtShiftDate.Text != string.Empty)
            {
                dateFormat = Convert.ToString(Session["MDateFormat"]);
                shiftDate = objcommon.DateTimeConvertion((dateFormat), txtShiftDate.Text, "D");
                DateTime dtCurrentDate = DateTime.Now;
                DateTime dtToDate = DateTime.Parse(shiftDate);
                TimeSpan diff = dtToDate.Subtract(dtCurrentDate);
                int day = diff.Days;
                if (day > 0)
                {
                    strScript = "alert('Timesheet entry should not be allowed to enter for future date');";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                    return;
                }
                else if (day < -660)
                {
                    strScript = "alert('Timesheet entry should not be allowed to enter for very past date');";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                    return;
                }
            }
            int fullDayCount = 0;
            int halfDayCount = 0;
            fullDayCount = objLeaveApplicationEventData.CheckLeaveApplication(Convert.ToInt32(Session["EmpAutoID"]), shiftDate, shiftDate, Convert.ToInt32(workFromHomeLeaveTypeID));
            halfDayCount = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(Session["EmpAutoID"]), shiftDate, shiftDate, "First Half", "Second Half");
            //if (fullDayCount == 0)
            if (fullDayCount != 0 || halfDayCount != 0)
            {
                DataSet dsCheck = new DataSet();
                dsCheck = objTimeSheet.validateTimeSheetAlreadyAvailable(shiftDate, Convert.ToInt64(Session["EmpAutoID"]));
                if (dsCheck.Tables.Count > 0)
                {
                    if (dsCheck.Tables[0].Rows.Count > 0)
                    {
                        strScript = "alert('Timesheet entry is already entered for this date');";
                        ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                        return;
                    }
                }
                if (ViewState["totalMinutes"] != null)
                {
                    int totalMinutes = (int)ViewState["totalMinutes"];
                    if (totalMinutes > 24 * 60)
                    {
                        strScript = "alert('You have entered timesheet more than 24 hours, please correct the timing');";
                        ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                        return;
                    }
                }
                {
                    objTimeSheet.FinalProgressUpdation(shiftDate, Convert.ToInt64(Session["EmpAutoID"]));
                    string strHtml = string.Empty;
                    DataTable dtTask = new DataTable();
                    if (ViewState["dtCurrentdayTask"] != null)
                    {
                        dtTask = (DataTable)ViewState["dtCurrentdayTask"];
                    }
                    else
                    {
                        BindCurrentDateTimeSheetEntries();
                        dtTask = (DataTable)ViewState["dtCurrentdayTask"];
                    }
                    DataSet dsEmployeeDetails = new DataSet();
                    string strEmpFirstName, strEmpLastName, strlevelName, strEmployeeCodeId, strEmployeeName = "", empEmailID = "";
                    dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(Session["EmpAutoID"]));
                    if (dsEmployeeDetails.Tables.Count > 0)
                    {
                        if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
                        {
                            strEmpFirstName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                            strEmpLastName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
                            strEmployeeCodeId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
                            strEmployeeName = strEmpFirstName + " " + strEmpLastName;
                            strlevelName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["levelName"]);
                            empEmailID = "";
                        }
                    }
                    DataSet dsEmailIdOfSanctionAuthority = new DataSet();
                    DataSet dsEmailIdOfReportingTo = new DataSet();
                    PermissionEventData objPermissionEventData = new PermissionEventData();
                    dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(Session["EmpAutoID"]));
                    dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(Session["EmpAutoID"]));
                    string strEmailIdSanctioningAuthority = string.Empty;
                    string strEmailIdReportingTo = string.Empty;
                    if (dsEmailIdOfSanctionAuthority != null)
                    {
                        if (dsEmailIdOfSanctionAuthority.Tables.Count > 0)
                        {
                            if (dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            {
                                if (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != "")
                                    {
                                        strEmailIdSanctioningAuthority = Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]);
                                    }
                                }
                            }
                        }
                    }
                    if (dsEmailIdOfReportingTo != null)
                    {
                        if (dsEmailIdOfReportingTo.Tables.Count > 0)
                        {
                            if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                            {
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != "")
                                    {
                                        strEmailIdReportingTo = Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                                    }
                                }
                            }
                        }
                    }
                    strHtml = buildPage(dtTask, strEmployeeName, shiftDate);
                    BindCurrentDateTimeSheetEntries();
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        SendMail(strHtml, empEmailID, strEmailIdReportingTo, empEmailID, shiftDate, strEmployeeName);
                    }
                    strScript = "alert('Timesheet entry saved successfully');";
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);
                    return;
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Unable to find Work from home requisition in leave application for selected date or your requisition is not approved by your supervisor,please get the approval first');", true);
                return;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Timesheet entry should be allowed in employees login alone');", true);
            return;
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in gvTaskEntry.Rows)
        {
            Label lblProjectTaskID = (Label)row.FindControl("lblProjectTaskID");
            if (lblProjectTaskID != null)
            {
                if (lblProjectTaskID.Text != "")
                    objTimeSheet.DeleteProgressTaskDetails(Convert.ToInt32(lblProjectTaskID.Text));
            }
        }
        txtShiftDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
    }
    private void SendMail(string strHtml, string fromEmailID, string ToEmailID, string ccEmailID, string entryDate, string empName)
    {
        string strFromEmailId = string.Empty;
        MailMessage mailMessage = new MailMessage();
        try
        {
            DataTable dtTableScript = new DataTable();

            if (fromEmailID != "")
            {
                mailMessage.From = new MailAddress(fromEmailID);
            }
            else
            {
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            }
            //mailMessage.From = new MailAddress("manikandan.rr@angleritech.com");
            if (ToEmailID != "")
                mailMessage.To.Add(new MailAddress(ToEmailID));
            if (ccEmailID != "")
                mailMessage.To.Add(new MailAddress(ccEmailID));
            mailMessage.Subject = "Timesheet Entry for " + entryDate + " | " + empName;
            mailMessage.Body = strHtml;
            mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?ApprovalType=TimesheetEntry");
            objcommon.SendMail(mailMessage);
        }
        catch
        {
            //blnCheckEmail = false;
        }
    }

    public string buildPage(DataTable myDT, string empName, string entryDate)
    {
        StringBuilder sb = new StringBuilder();
        //HTML header
        sb.Append("<table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>");
        sb.Append("<tr><td>&nbsp;</td></tr>");
        sb.Append("<tr>");
        sb.Append("<td colspan='2' align='center' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #003466; font-weight: bold;'> Timesheet Entry for the Day</td>");
        sb.Append("</tr><tr>");
        sb.Append("<td align='left' width='58%' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #003466; font-weight: bold;'>Name&nbsp;:&nbsp;");
        sb.Append(empName);
        sb.Append("</td><td align = 'right' width = '42%' style = 'font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #003466; font-weight: bold;'>Date &nbsp;&nbsp;:&nbsp;");
        sb.Append(entryDate);
        sb.Append("</td>");
        sb.Append("</tr><tr><td>&nbsp;</td></tr><tr><td colspan='2'>");
       
        sb.Append("<table width='100%' border='0' cellpadding='4' cellspacing='1' bgcolor='#003466'>");
        sb.Append("<tr align='center' valign='middle'>");
        string colName = string.Empty;
        foreach (DataColumn Col in myDT.Columns)
        {
            switch (Col.ColumnName)
            {
                case "Project_Name":
                case "TaskDescription":
                case "TaskName":
                case "SpentHours":
                case "TaskHours":
                    if (Col.ColumnName == "Project_Name")
                    {
                        colName = "Project";
                        sb.Append("<td width='30%' height='19' align='center' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #FFFFFF; font-weight: bold;'>" + colName.ToString() + "</td>");
                    }
                    if (Col.ColumnName == "TaskDescription")
                    {
                        colName = "Description";
                        sb.Append("<td width='25%' height='19' align='center' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #FFFFFF; font-weight: bold;'>" + colName.ToString() + "</td>");
                    }
                    if (Col.ColumnName == "TaskName")
                    {
                        colName = "Task Name";
                        sb.Append("<td width='25%' height='19' align='center' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #FFFFFF; font-weight: bold;'>" + colName.ToString() + "</td>");
                    }
                    if (Col.ColumnName == "SpentHours")
                    {
                        colName = "Spent Hours";
                        sb.Append("<td width='10%' height='19' align='center' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #FFFFFF; font-weight: bold;'>" + colName.ToString() + "</td>");
                    }
                    if (Col.ColumnName == "TaskHours")
                    {
                        colName = "Task Hours";
                        sb.Append("<td width='10%' height='19' align='center' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;color: #FFFFFF; font-weight: bold;'>" + colName.ToString() + "</td>");
                    }
                    break;
            }

        }
        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            if (intIncrement % 2 == 0)
            {
                sb.Append("<tr  bgcolor='fffffb'>");
            }
            else
            {
                sb.Append("<tr  bgcolor='E5EAF0'>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                switch (Col.ColumnName)
                {
                    case "Project_Name":                   
                        sb.Append("<td width='30%' height='19' align='left' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;'>" + Row[Col.ColumnName].ToString() + "</td>");
                        break;
                    case "TaskDescription":
                    case "TaskName":
                        sb.Append("<td width='25%' height='19' align='left' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;'>" + Row[Col.ColumnName].ToString() + "</td>");
                        break;
                    case "SpentHours":
                    case "TaskHours":
                        sb.Append("<td width='10%' height='19' align='left' style='font-size: 13; font-family: Arial, Helvetica, sans-serif;'>" + Row[Col.ColumnName].ToString() + "</td>");
                        break;
                }
            }
            sb.Append(" </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</td></tr>");
        sb.Append("</table>");
        sb.Append("<br/>");
        sb.Append("<a style='font-size: 12; font-family: Arial, Helvetica, sans-serif;font-weight: bold;' href=<<LinkData>>>Click here for approval</a>");
        return sb.ToString();
    }

    public void getLeaveTypeDetails()
    {
        DataSet dsleaveType = new DataSet();
        dsleaveType = leaveTypeData.SelectLeaveTypeDetails(Convert.ToString(Session["UserGroupName"]));
        if (dsleaveType.Tables.Count > 0)
        {
            if (dsleaveType.Tables[0].Rows.Count > 0)
            {
                dsleaveType.Tables[0].DefaultView.RowFilter = "LeaveType='WFH'";
                DataTable dt = dsleaveType.Tables[0].DefaultView.ToTable();
                if (dt.Rows.Count > 0)
                {
                    workFromHomeLeaveTypeID = Convert.ToInt32(dt.Rows[0]["LeaveType_Id"]);
                }
            }
        }
    }
    public string GetStatusBasedOnAllocation(string inEmployeeCodeId)
    {
        DataSet dsReportingPersons = new DataSet();
        DataTable dtReportingPersons = new DataTable();
        string strManualTimeEntryStatus = string.Empty;
        Int64 intReportTo = 0, intLeave_Sanc_Authority = 0;
        dsReportingPersons = objEmployee.GetReportingToSanctionAuthorityByCodeID(inEmployeeCodeId);
        dtReportingPersons = dsReportingPersons.Tables[0];
        if (dtReportingPersons.Rows.Count > 0)
        {
            if (dtReportingPersons.Rows[0]["Reporting_To"] != DBNull.Value && dtReportingPersons.Rows[0]["Reporting_To"].ToString() != string.Empty)
                intReportTo = Int64.Parse(dtReportingPersons.Rows[0]["Reporting_To"].ToString());
            if (dtReportingPersons.Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dtReportingPersons.Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
                intLeave_Sanc_Authority = Int64.Parse(dtReportingPersons.Rows[0]["Leave_Sanc_Authority"].ToString());
        }
        if (intReportTo != 0 && intLeave_Sanc_Authority != 0 && intReportTo != intLeave_Sanc_Authority)
            strManualTimeEntryStatus = "Pending";
        else
            strManualTimeEntryStatus = "Forwarded";
        return (strManualTimeEntryStatus);
    }
}