protected void btnStatusSave_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }

            string[] cmd = btn.CommandArgument.Split('~');             // recordType, recordID, recordSubID, taskStep, taskType

            EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(Convert.ToInt32(cmd[0]), Convert.ToDecimal(cmd[1]));

            if (auditQuestion != null)
            {
                auditQuestion.Status            = ddlAnswerStatus.SelectedValue.ToString();
                auditQuestion.ResolutionComment = tbResolutionComment.Text.ToString();
                if (auditQuestion.Status.Equals("03"))
                {
                    // update the complete date with the local date/time of the plant
                    AUDIT    audit     = EHSAuditMgr.SelectAuditById(entities, auditQuestion.AuditId);
                    PLANT    plant     = SQMModelMgr.LookupPlant((decimal)audit.DETECT_PLANT_ID);
                    DateTime localTime = WebSiteCommon.LocalTime(DateTime.UtcNow, plant.LOCAL_TIMEZONE);
                    auditQuestion.CompleteDate = localTime;
                }
                EHSAuditMgr.UpdateAnswer(auditQuestion);
            }
            UpdateTaskList("update");
        }
        protected void lnkDeleteTask_OnClick(object sender, EventArgs e)
        {
            // we are only marking the status as deleteded, not physically deleting the task.
            lblErrorMessage.Text = "";
            LinkButton btn = (LinkButton)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }
            TaskStatusMgr taskMgr = new TaskStatusMgr().CreateNew(0, 0);
            TASK_STATUS   task    = taskMgr.SelectTask(Convert.ToDecimal(btn.CommandArgument));

            taskMgr.UpdateTaskStatus(task, TaskStatus.Delete);
            taskMgr.UpdateTask(task);
            taskMgr.UpdateTaskList(task.RECORD_ID);
            if (OnTaskAdd != null)
            {
                OnTaskAdd("added", task.RECORD_ID, (decimal)task.RECORD_SUBID);
            }
            if (task.RECORD_TYPE == (int)TaskRecordType.Audit)             // update the Question Status when adding tasks for an audit followup.
            {
                EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(task.RECORD_ID, (decimal)task.RECORD_SUBID);

                if (auditQuestion != null)
                {
                    auditQuestion.Status = "02";
                    EHSAuditMgr.UpdateAnswer(auditQuestion);
                }
                SessionManager.ReturnRecordID = task.RECORD_ID;
                SessionManager.ReturnObject   = "AddTask";
                SessionManager.ReturnStatus   = true;
            }
        }
        private void UpdateAnswerStatus(decimal auditID, decimal questionID)
        {
            EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(auditID, questionID);

            if (auditQuestion != null)
            {
                if (TaskXLATList == null || TaskXLATList.Count == 0)
                {
                    TaskXLATList = SQMBasePage.SelectXLATList(new string[1] {
                        "AUDIT_EXCEPTION_STATUS"
                    });
                }
                ddlAnswerStatus.DataTextField  = "DESCRIPTION";
                ddlAnswerStatus.DataValueField = "XLAT_CODE";
                ddlAnswerStatus.DataSource     = TaskXLATList;
                ddlAnswerStatus.DataBind();

                if (auditQuestion.Status == null || auditQuestion.Status == "")
                {
                    ddlAnswerStatus.SelectedIndex = 0;
                }
                else
                {
                    ddlAnswerStatus.SelectedValue = auditQuestion.Status;
                }

                btnStatusSave.CommandArgument = auditID + "~" + questionID;

                string script = "function f(){OpenUpdateAnswerStatusWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
            }
        }
        protected void AddAttach(decimal auditId, decimal questionId)
        {
            EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(auditId, questionId);
            AUDIT            audit         = EHSAuditMgr.SelectAuditById(new PSsqmEntities(), auditId);
            int recordType = (int)TaskRecordType.Audit;

            // before we call the radWindow, we need to update the page?
            uclAttachWin.OpenManageAttachmentsWindow(recordType, audit.AUDIT_ID, auditQuestion.QuestionId.ToString(), Resources.LocalizedText.AttachmentsUpload.ToString(), Resources.LocalizedText.AttachmentsForAssessment.ToString());
        }
        protected void rgAuditAnswers_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem     item = (GridDataItem)e.Item;
                HiddenField      hf;
                LinkButton       lnk;
                Label            lbl;
                EHSAuditQuestion data = (EHSAuditQuestion)e.Item.DataItem;

                lnk = (LinkButton)e.Item.FindControl("lnkAddTask");
                lnk.CommandArgument = data.AuditId.ToString() + "," + data.QuestionId.ToString();
                string buttonText = Resources.LocalizedText.AssignTask + "(" + data.TasksAssigned.ToString() + ")";
                lnk.Text = buttonText;

                lnk = (LinkButton)e.Item.FindControl("lnkAddAttach");
                lnk.CommandArgument = data.AuditId.ToString() + "," + data.QuestionId.ToString();
                buttonText          = Resources.LocalizedText.Attachments + "(" + data.FilesAttached.ToString() + ")";
                lnk.Text            = buttonText;

                lnk = (LinkButton)e.Item.FindControl("lnkUpdateStatus");
                lnk.CommandArgument = data.AuditId.ToString() + "," + data.QuestionId.ToString();
                if (!hdnAuditPerson.Value.ToString().Equals(SessionManager.UserContext.Person.PERSON_ID.ToString()))
                {
                    lnk.Visible = false;
                }

                if (TaskXLATList == null || TaskXLATList.Count == 0)
                {
                    TaskXLATList = SQMBasePage.SelectXLATList(new string[1] {
                        "AUDIT_EXCEPTION_STATUS"
                    });
                }

                lbl = (Label)e.Item.FindControl("lblAnswerStatus");
                if (data.Status == null)
                {
                    lbl.Text = TaskXLATList.Where(l => l.XLAT_GROUP == "AUDIT_EXCEPTION_STATUS" && l.XLAT_CODE == "01").FirstOrDefault().DESCRIPTION;
                }
                else
                {
                    lbl.Text = TaskXLATList.Where(l => l.XLAT_GROUP == "AUDIT_EXCEPTION_STATUS" && l.XLAT_CODE == data.Status.ToString()).FirstOrDefault().DESCRIPTION;
                }

                lbl = (Label)e.Item.FindControl("lblResolutionDate");
                if (data.CompleteDate == null || data.CompleteDate.Year == 1)
                {
                    lbl.Text = "";
                }
                else
                {
                    lbl.Text = data.CompleteDate.ToString("MM/dd/yyyy");
                }
            }
        }
        private void AddTask(decimal auditID, decimal questionID)
        {
            int              recordType    = (int)TaskRecordType.Audit;
            AUDIT            audit         = EHSAuditMgr.SelectAuditById(new PSsqmEntities(), auditID);
            EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(auditID, questionID);

            //List<TASK_STATUS> tasks = TaskMgr.AuditTaskListByRecord(recordType, auditID, questionID);
            uclTask.BindTaskAdd(recordType, auditQuestion.AuditId, auditQuestion.QuestionId, "350", "T", auditQuestion.QuestionText, (decimal)audit.DETECT_PLANT_ID, "");
            string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
        }
        /// <summary>
        /// Select a list of all possible audit questions
        /// </summary>
        public static List <EHSAuditQuestion> SelectAuditQuestionList()
        {
            var questionList = new List <EHSAuditQuestion>();

            try
            {
                var entities     = new PSsqmEntities();
                var allQuestions = (from q in entities.AUDIT_QUESTION.Include("AUDIT_QUESTION_LANG") select q).ToList();

                foreach (var q in allQuestions)
                {
                    var typeInfo = (from ti in entities.AUDIT_QUESTION_TYPE
                                    where q.AUDIT_QUESTION_TYPE_ID == ti.AUDIT_QUESTION_TYPE_ID
                                    select ti).FirstOrDefault();

                    var newQuestion = new EHSAuditQuestion()
                    {
                        QuestionId         = q.AUDIT_QUESTION_ID,
                        QuestionText       = q.QUESTION_TEXT,
                        QuestionType       = (EHSAuditQuestionType)q.AUDIT_QUESTION_TYPE_ID,
                        HasMultipleChoices = typeInfo.HAS_MULTIPLE_CHOICES,
                        HelpText           = q.HELP_TEXT
                    };

                    if (newQuestion.HasMultipleChoices)
                    {
                        List <EHSAuditAnswerChoice> choices = (from qc in entities.AUDIT_QUESTION_CHOICE
                                                               where qc.AUDIT_QUESTION_ID == q.AUDIT_QUESTION_ID
                                                               orderby qc.SORT_ORDER
                                                               select new EHSAuditAnswerChoice
                        {
                            Value = qc.QUESTION_CHOICE_VALUE,
                            IsCategoryHeading = qc.IS_CATEGORY_HEADING
                        }).ToList();
                        if (choices.Count > 0)
                        {
                            newQuestion.AnswerChoices = choices;
                        }
                    }
                    questionList.Add(newQuestion);
                }

                questionList.OrderBy(field => field.QuestionText);
                questionList.OrderBy(field => field.QuestionType);
            }
            catch (Exception e)
            {
                //SQMLogger.LogException(e);
            }

            return(questionList);
        }
        private void UpdateTaskList(string cmd, decimal recordID, decimal recordSubID)
        {
            // update the status when a task is added
            if (cmd == "added")
            {
                EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(recordID, recordSubID);

                if (auditQuestion != null)
                {
                    auditQuestion.Status = "02";
                    EHSAuditMgr.UpdateAnswer(auditQuestion);
                }
                SearchAudits();
            }
        }
        /// <summary>
        /// Select a list of all audit questions by topic
        /// </summary>
        public static List <EHSAuditQuestion> SelectAuditQuestionList(decimal auditTypeId, decimal auditTopicId, decimal auditId)
        {
            var questionList = new List <EHSAuditQuestion>();

            try
            {
                var entities           = new PSsqmEntities();
                var activeQuestionList = new List <AUDIT_TYPE_TOPIC_QUESTION>();
                var auditAnswers       = new List <decimal>();
                if (auditId > 0)
                {
                    auditAnswers = (from a in entities.AUDIT_ANSWER
                                    where a.AUDIT_ID == auditId
                                    select a.AUDIT_QUESTION_ID).ToList();
                }
                if (auditTopicId > 0)
                {
                    if (auditId == 0)
                    {
                        // no audit id means add mode, so we only want to get active questions
                        activeQuestionList = (from q in entities.AUDIT_TYPE_TOPIC_QUESTION
                                              where q.AUDIT_TYPE_ID == auditTypeId && q.AUDIT_TOPIC_ID == auditTopicId && !q.INACTIVE
                                              orderby q.SORT_ORDER
                                              select q
                                              ).ToList();
                    }
                    else
                    {
                        // need to only select questions that appear in the specific audit
                        activeQuestionList = (from q in entities.AUDIT_TYPE_TOPIC_QUESTION
                                              where q.AUDIT_TYPE_ID == auditTypeId && q.AUDIT_TOPIC_ID == auditTopicId && auditAnswers.Contains(q.AUDIT_QUESTION_ID)
                                              orderby q.SORT_ORDER
                                              select q
                                              ).ToList();
                    }
                }
                else
                {
                    if (auditId == 0)
                    {
                        // no audit id means add mode, so we only want to get active questions
                        activeQuestionList = (from q in entities.AUDIT_TYPE_TOPIC_QUESTION
                                              where q.AUDIT_TYPE_ID == auditTypeId && !q.INACTIVE
                                              orderby q.AUDIT_TOPIC_ID, q.SORT_ORDER
                                              select q
                                              ).ToList();
                    }
                    else
                    {
                        // need to only select questions that appear in the specific audit
                        activeQuestionList = (from q in entities.AUDIT_TYPE_TOPIC_QUESTION
                                              where q.AUDIT_TYPE_ID == auditTypeId && auditAnswers.Contains(q.AUDIT_QUESTION_ID)
                                              orderby q.AUDIT_TOPIC_ID, q.SORT_ORDER
                                              select q
                                              ).ToList();
                    }
                }

                foreach (var aq in activeQuestionList)
                {
                    var questionInfo = (from qi in entities.AUDIT_QUESTION.Include("AUDIT_QUESTION_LANG")
                                        where qi.AUDIT_QUESTION_ID == aq.AUDIT_QUESTION_ID
                                        select qi).FirstOrDefault();

                    var typeInfo = (from ti in entities.AUDIT_QUESTION_TYPE
                                    where questionInfo.AUDIT_QUESTION_TYPE_ID == ti.AUDIT_QUESTION_TYPE_ID
                                    select ti).FirstOrDefault();

                    var topicInfo = (from tp in entities.AUDIT_TOPIC
                                     where aq.AUDIT_TOPIC_ID == tp.AUDIT_TOPIC_ID
                                     select tp).FirstOrDefault();

                    var newQuestion = new EHSAuditQuestion()
                    {
                        QuestionId = questionInfo.AUDIT_QUESTION_ID,
                        //QuestionText = questionInfo.QUESTION_TEXT,
                        QuestionText       = AuditQuestionText(questionInfo, SessionManager.SessionContext.Language().NLS_LANGUAGE),
                        QuestionType       = (EHSAuditQuestionType)questionInfo.AUDIT_QUESTION_TYPE_ID,
                        HasMultipleChoices = typeInfo.HAS_MULTIPLE_CHOICES,
                        IsRequired         = questionInfo.IS_REQUIRED,
                        IsRequiredClose    = questionInfo.IS_REQUIRED_CLOSE,
                        HelpText           = questionInfo.HELP_TEXT,
                        StandardType       = questionInfo.STANDARD_TYPE,
                        TopicId            = topicInfo.AUDIT_TOPIC_ID,
                        TopicTitle         = topicInfo.TITLE
                    };

                    if (newQuestion.HasMultipleChoices)
                    {
                        List <EHSAuditAnswerChoice> choices = (from qc in entities.AUDIT_QUESTION_CHOICE
                                                               where qc.AUDIT_QUESTION_ID == questionInfo.AUDIT_QUESTION_ID
                                                               orderby qc.SORT_ORDER
                                                               select new EHSAuditAnswerChoice
                        {
                            Value = qc.QUESTION_CHOICE_VALUE,
                            IsCategoryHeading = qc.IS_CATEGORY_HEADING,
                            ChoiceWeight = qc.CHOICE_WEIGHT,
                            ChoicePositive = qc.CHOICE_POSITIVE
                        }).ToList();
                        if (choices.Count > 0)
                        {
                            newQuestion.AnswerChoices = choices;
                        }
                    }

                    //// Question control logic
                    //newQuestion.QuestionControls = (from qc in entities.AUDIT_QUESTION_CONTROL
                    //								where qc.AUDIT_TYPE_ID == auditTypeId &&
                    //								qc.AUDIT_TOPIC_ID == auditTopicId &&
                    //								qc.AUDIT_QUESTION_ID == newQuestion.QuestionId
                    //								orderby qc.PROCESS_ORDER
                    //								select qc).ToList();

                    questionList.Add(newQuestion);
                }
            }
            catch (Exception e)
            {
                //SQMLogger.LogException(e);
            }

            return(questionList);
        }
        protected void btnTaskUpdate_Click(object sender, EventArgs e)
        {
            PSsqmEntities ctx = new PSsqmEntities();

            lblErrorMessage.Text = "";
            Button btn = (Button)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }

            TaskStatusMgr taskMgr = new TaskStatusMgr().CreateNew(0, 0);
            TASK_STATUS   task    = taskMgr.SelectTask(Convert.ToDecimal(btn.CommandArgument));

            //task.RECORD_TYPE = recordType;
            //task.RECORD_ID = recordID;
            //task.RECORD_SUBID = recordSubID;
            //task.TASK_STEP = taskStep;
            //task.TASK_TYPE = taskType;
            //task.TASK_SEQ = 0;
            task.DUE_DT = rdpTaskDueDT.SelectedDate;
            //task.RESPONSIBLE_ID = Convert.ToDecimal(ddlAssignPerson.SelectedValue.ToString());
            //task.DETAIL = lblTaskDetailValue.Text.ToString(); // this is the original detail, so we don't change it.
            //task.DESCRIPTION = tbTaskDescription.Text.ToString();
            task.COMMENTS = tbTaskComments.Text.ToString();
            //task.STATUS = ((int)TaskStatus.New).ToString();
            //task.CREATE_DT = SessionManager.UserContext.LocalTime != null ? SessionManager.UserContext.LocalTime : DateTime.UtcNow;
            //task.CREATE_ID = SessionManager.UserContext.Person.PERSON_ID;

            taskMgr.UpdateTask(task);
            taskMgr.UpdateTaskList(task.RECORD_ID);
            // send email
            PERSON assignTo = SQMModelMgr.LookupPerson(ctx, (decimal)task.RESPONSIBLE_ID, "", false);

            EHSNotificationMgr.NotifyTaskAssigment(task, assignTo.PLANT_ID);

            // reset the fields for the next add
            ddlAssignPersonAdd.SelectedValue = "";
            tbTaskDescriptionAdd.Text        = "";
            rdpTaskDueDTAdd.SelectedDate     = DateTime.Today;

            if (OnTaskAdd != null)
            {
                OnTaskAdd("added", task.RECORD_ID, (decimal)task.RECORD_SUBID);
            }
            if (task.RECORD_TYPE == (int)TaskRecordType.Audit)             // update the Question Status when adding tasks for an audit followup.
            {
                EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(task.RECORD_ID, (decimal)task.RECORD_SUBID);

                if (auditQuestion != null)
                {
                    auditQuestion.Status = "02";
                    EHSAuditMgr.UpdateAnswer(auditQuestion);
                }
                //SessionManager.ReturnRecordID = task.RECORD_ID;
                //SessionManager.ReturnObject = "AddTask";
                //SessionManager.ReturnStatus = true;
            }

            if (Page.Request.Url.ToString().Contains("AssessmentForm"))
            {
                // now update the list and stay on the popup if adding through assessment form
                BindTaskAdd(task.RECORD_TYPE, task.RECORD_ID, (decimal)task.RECORD_SUBID, task.TASK_STEP, task.TASK_TYPE, lblTaskDetailValue.Text.ToString(), assignTo.PLANT_ID, "");
                lblErrorMessage.Text = "";

                string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
            }
            else
            {
                SessionManager.ReturnRecordID = task.RECORD_ID;
                SessionManager.ReturnObject   = "UpdateTask";
                SessionManager.ReturnStatus   = true;

                if (OnTaskUpdate != null)
                {
                    OnTaskUpdate("update");
                }
            }
        }
        protected void btnTaskAdd_Click(object sender, EventArgs e)
        {
            PSsqmEntities ctx = new PSsqmEntities();

            lblErrorMessage.Text = "";
            Button btn = (Button)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }

            string[] cmd         = btn.CommandArgument.Split('~');     // recordType, recordID, recordSubID, taskStep, taskType, plantID
            int      recordType  = Convert.ToInt32(cmd[0]);
            decimal  recordID    = Convert.ToDecimal(cmd[1]);
            decimal  recordSubID = Convert.ToDecimal(cmd[2]);
            string   taskStep    = cmd[3];
            string   taskType    = cmd[4];

            decimal plantID = 0;

            decimal.TryParse(cmd[5], out plantID);

            // make sure that the Assign To Employee has been selected
            if (ddlAssignPersonAdd.SelectedValue.ToString().Equals(""))
            {
                // I don't think we need to bind the list at this point
                BindTaskAdd(recordType, recordID, recordSubID, taskStep, taskType, lblTaskDetailValueAdd.Text.ToString(), plantID, "");
                lblErrorMessage.Text = lblErrRequiredInputs.Text.ToString();
                string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
            }
            else
            {
                TaskStatusMgr taskMgr = new TaskStatusMgr();
                taskMgr.Initialize(recordType, recordID);
                TASK_STATUS task = new TASK_STATUS();
                task.RECORD_TYPE    = recordType;
                task.RECORD_ID      = recordID;
                task.RECORD_SUBID   = recordSubID;
                task.TASK_STEP      = taskStep;
                task.TASK_TYPE      = taskType;
                task.TASK_SEQ       = 0;
                task.DUE_DT         = rdpTaskDueDTAdd.SelectedDate;
                task.RESPONSIBLE_ID = Convert.ToDecimal(ddlAssignPersonAdd.SelectedValue.ToString());
                task.DETAIL         = lblTaskDetailValueAdd.Text.ToString();
                task.DESCRIPTION    = tbTaskDescriptionAdd.Text.ToString();
                task.STATUS         = ((int)TaskStatus.New).ToString();
                task.CREATE_DT      = SessionManager.UserContext.LocalTime != null ? SessionManager.UserContext.LocalTime : DateTime.UtcNow;
                task.CREATE_ID      = SessionManager.UserContext.Person.PERSON_ID;

                taskMgr.CreateTask(task);
                taskMgr.UpdateTaskList(task.RECORD_ID);
                // send email
                PERSON assignTo = SQMModelMgr.LookupPerson(ctx, (decimal)task.RESPONSIBLE_ID, "", false);
                EHSNotificationMgr.NotifyTaskAssigment(task, assignTo.PLANT_ID);

                // reset the fields for the next add
                ddlAssignPersonAdd.SelectedValue = "";
                tbTaskDescriptionAdd.Text        = "";
                rdpTaskDueDTAdd.SelectedDate     = DateTime.Today;

                if (OnTaskAdd != null)
                {
                    OnTaskAdd("added", task.RECORD_ID, (decimal)task.RECORD_SUBID);
                }
                if (recordType == (int)TaskRecordType.Audit)                 // update the Question Status when adding tasks for an audit followup.
                {
                    EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(recordID, recordSubID);

                    if (auditQuestion != null)
                    {
                        auditQuestion.Status = "02";
                        EHSAuditMgr.UpdateAnswer(auditQuestion);
                    }
                    //SessionManager.ReturnRecordID = task.RECORD_ID;
                    //SessionManager.ReturnObject = "AddTask";
                    //SessionManager.ReturnStatus = true;
                }

                if (Page.Request.Url.ToString().Contains("AssessmentForm"))
                {
                    // now update the list and stay on the popup
                    BindTaskAdd(recordType, recordID, recordSubID, taskStep, taskType, lblTaskDetailValueAdd.Text.ToString(), plantID, "");
                    lblErrorMessage.Text = "";
                    string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
                }
                else
                {
                    SessionManager.ReturnRecordID = task.RECORD_ID;
                    SessionManager.ReturnObject   = "AddTask";
                    SessionManager.ReturnStatus   = true;
                }
            }
        }