public void Initialize(int surveyId, int questionId, int displayOrder, int pageNumber)
        {
            string baseURL = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

            insertLink.HRef = string.Format("{0}/InsertQuestion.aspx?SurveyID={1}&DisplayOrder={2}&Page={3}&MenuIndex={4}&QuestionId={5}",
            UINavigator.AdminRoot, surveyId, displayOrder + 1, pageNumber, -1, questionId);

            var questions = new Questions().GetQuestions(surveyId, null);
            var qEnumeration = questions.Questions.OrderBy(x => x.DisplayOrder);
            var prevQuestion = qEnumeration.LastOrDefault(x => x.DisplayOrder < displayOrder);
            var nextQuestion = qEnumeration.FirstOrDefault(x => x.DisplayOrder > displayOrder);
            cloneLink.CommandArgument = questionId.ToString();

            if (prevQuestion != null)
            {
                string qtype = prevQuestion.SelectionModeId == 4 ? "Matrix" : "Single";
                string qstr = prevQuestion.SelectionModeId == 4 ? "parent" : "";
                prevLink.HRef = string.Format("{0}/Edit{1}Question.aspx?surveyid={2}&{3}questionid={4}&MenuIndex={5}",
                   UINavigator.AdminRoot, qtype, surveyId, qstr, prevQuestion.QuestionId, -1);
            }
            else prevLink.Disabled = true;

            if (nextQuestion != null)
            {
                string qstr = nextQuestion.SelectionModeId == 4 ? "parent" : "";
                string qtype = nextQuestion.SelectionModeId == 4 ? "Matrix" : "Single";
                nextLink.HRef = string.Format("{0}/Edit{1}Question.aspx?surveyid={2}&{3}questionid={4}&MenuIndex={5}",
                UINavigator.AdminRoot,qtype, surveyId, qstr, nextQuestion.QuestionId, -1);
            }
            else nextLink.Disabled = true;
        }
        protected void cloneLink_Click1(object sender, System.EventArgs e)
        {
            int questionId = int.Parse(((LinkButton)sender).CommandArgument);
            var question = new Questions().GetQuestionById(questionId, null);
            var newQuestion = new Question().CloneQuestionById(questionId);

            var q = newQuestion.Questions[0];
            if (q.SelectionModeId == 4)
                UINavigator.NavigateToMatrixQuestionEdit(q.SurveyId, q.QuestionId, -1, -1);
            else
                UINavigator.NavigateToSingleQuestionEdit(q.SurveyId, q.QuestionId, -1, -1);
        }
		void BuildQuestionList()
		{
			QuestionData _questionsData = new Questions().GetAnswerableQuestionWithoutChilds(SurveyId);
			int currentPage = 1,
				previousDisplayOrder = 0,
				totalPages = new Surveys().GetPagesNumber(SurveyId);
			
			Table questionsContainer = new Table();
			questionsContainer.Width = Unit.Percentage(100);
			Table questionTable = new Table();
			questionTable.CellSpacing = 2;
			questionTable.CellPadding = 4;
			questionTable.CssClass = "questionBuilder";
				
			questionTable.Rows.Add(BuildPageBreakOptionsRow(currentPage, totalPages,previousDisplayOrder));
			foreach (QuestionData.QuestionsRow question in _questionsData.Questions.Rows)
			{
				while (question.PageNumber > currentPage)
				{
					currentPage++;

					questionsContainer.Rows.Add(BuildRow(questionTable));
					EditAnswersPlaceHolder.Controls.Add(questionsContainer);

					// Creates a new page
					questionsContainer = new Table();
					questionsContainer.Width = Unit.Percentage(100);
					questionTable = new Table();
					questionTable.CellSpacing = 2;
					questionTable.CellPadding = 4;
					questionTable.CssClass = "questionBuilder";
					questionTable.Rows.Add(BuildPageBreakOptionsRow(currentPage, totalPages,previousDisplayOrder));
				}

				if (question.PageNumber == currentPage)
				{
					AddQuestionWebControl(questionTable, question);
					previousDisplayOrder = question.DisplayOrder;
				}
			}

			questionsContainer.Rows.Add(BuildRow(questionTable));
			EditAnswersPlaceHolder.Controls.Add(questionsContainer);
		}
        void EstablishLibraryOrNot()
        {
            QuestionData question = new Questions().GetQuestionById(_questionId, LanguagesDropdownlist.SelectedValue);
            QuestionData.QuestionsRow questionRow = question.Questions[0];
            ViewState["LibraryId"] = questionRow.IsLibraryIdNull() ? -1 : questionRow.LibraryId;
            if (!questionRow.IsLibraryIdNull() && !NSurveyUser.Identity.IsAdmin)
            {
                CheckRight(NSurveyRights.ManageLibrary, true);
            }

            // Can the question have answers
        }
        private void ExportXMLButton_Click(object sender, System.EventArgs e)
        {
            Response.Charset = "utf-8";
            Response.ContentType = "application/octet-stream";

            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_question" + _parentQuestionId + ".xml\"");

            NSurveyQuestion questionForm = new Questions().GetQuestionForExport(_parentQuestionId);
            questionForm.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);
            Response.End();
        }
 private void BindChildQuestions()
 {
     MatrixChildQuestionData childQuestions = new MatrixChildQuestionData();
     childQuestions = new Questions().GetMatrixChildQuestions(_parentQuestionId, ChildsLanguageDropdownlist.SelectedValue);
     RowsDataGrid.DataSource = childQuestions;
     RowsDataGrid.DataMember = "ChildQuestions";
     RowsDataGrid.DataKeyField = "QuestionID";
     RowsDataGrid.DataBind();
 }
		protected override string GenerateQuestionsReport(bool onlyAnswered)
		{
			StringBuilder questionsReport = new StringBuilder();
			_questionData = new Questions().GetQuestionHierarchy(_surveyId);

			questionsReport.Append(Environment.NewLine + "<br />" + ResourceManager.GetString("SurveyAnswersTitle") + Environment.NewLine + "<br />");
			questionsReport.Append("-----------------------------------------" + Environment.NewLine + "<br />");

			QuestionData.QuestionsRow[] parentQuestions = GetParentQuestions();

			for (int i=0;i<parentQuestions.Length;i++)
			{
				string questionText = ((QuestionData.QuestionsRow)parentQuestions[i]).QuestionText;
				questionText = questionText.Replace("<br />", Environment.NewLine + "<br />");
				questionText = 	new PipeManager().PipeValuesInText(((QuestionData.QuestionsRow)parentQuestions[i]).QuestionId, questionText, _voterAnswers.VotersAnswers, null);

				if (System.Web.HttpContext.Current != null)
				{
					questionText = System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ");
				}

				// Check if the question has childs
				string filter = string.Format("ParentQuestionID = {0}", ((QuestionData.QuestionsRow)parentQuestions[i]).QuestionId); 
				QuestionData.QuestionsRow[] childQuestions = (QuestionData.QuestionsRow[])_questionData.Questions.Select(filter,"DisplayOrder", DataViewRowState.CurrentRows);
				if (childQuestions.Length == 0)
				{
					StringBuilder answerReport = new StringBuilder();

					for (int sectionNumber=0;sectionNumber<=GetQuestionSectionCount(((QuestionData.QuestionsRow)parentQuestions[i]).QuestionId);sectionNumber++)
					{
						answerReport.Append(GenerateAnswersReport(((QuestionData.QuestionsRow)parentQuestions[i]).QuestionId, onlyAnswered, sectionNumber));
						answerReport.Append(Environment.NewLine + "<br />");
					}
					
					if (answerReport.Length > 0 || !onlyAnswered)
					{

						questionsReport.Append( questionText + Environment.NewLine + "<br />");
						questionsReport.Append(answerReport);
						if (isScored)
						{
							questionsReport.Append(Environment.NewLine + "<br />");
							questionsReport.Append(ResourceManager.GetString("QuestionScoreLabel")+ _questionScore);
						}
						_totalScore += _questionScore;
						questionsReport.Append(Environment.NewLine + "<br />" + Environment.NewLine + "<br />");
					}
					_questionScore = 0;
				}
				else
				{
					questionsReport.Append( "-----" + Environment.NewLine + "<br />");
					questionsReport.Append( questionText + Environment.NewLine + "<br />" + Environment.NewLine + "<br />" );
					for (int sectionNumber=0;sectionNumber<=GetMatrixSectionCount(new DataView(_questionData.Questions,filter,"DisplayOrder", DataViewRowState.CurrentRows));sectionNumber++)
					{
						questionsReport.Append(GenerateMatrixReport(childQuestions, onlyAnswered, sectionNumber));
						questionsReport.Append(Environment.NewLine + "<br />");
					}
					questionsReport.Append( "-----"+ Environment.NewLine + "<br />");
					questionsReport.Append(Environment.NewLine + "<br />" + Environment.NewLine + "<br />");
				}
			}

			return questionsReport.ToString();
		}
        /// <summary>
        /// Check if we need to hide / skip the question depending on the
        /// skip logic rules rules
        /// </summary>
        public bool SkipQuestion(int questionId, VoterAnswersData voterAnswers, bool evaluateScores)
        {
            SkipLogicRuleData questionSkipLogicRules = new Questions().GetQuestionSkipLogicRules(questionId);
            if (questionSkipLogicRules.SkipLogicRules.Rows.Count <= 0)
            {
                return false;
            }
            DataRow[] rowArray = null;
            foreach (SkipLogicRuleData.SkipLogicRulesRow row in questionSkipLogicRules.SkipLogicRules.Rows)
            {
                int num = evaluateScores ? this.GetQuestionAnswersScore(row.QuestionId, voterAnswers) : 0;
                if ((evaluateScores && (row.ConditionalOperator == 3)) && (num == row.Score))
                {
                    return true;
                }
                if ((evaluateScores && (row.ConditionalOperator == 4)) && (num < row.Score))
                {
                    return true;
                }
                if ((evaluateScores && (row.ConditionalOperator == 5)) && (num > row.Score))
                {
                    return true;
                }
                if ((evaluateScores && (row.ConditionalOperator == 6)) && ((num >= row.Score) && (num <= row.ScoreMax)))
                {
                    return true;
                }
                if (!row.IsAnswerIdNull() && !row.IsTextFilterNull())
                {
                    string expression = new Survey().EscapeFilterString(row.TextFilter);
                    if ((!row.IsExpressionOperatorNull() && (row.ExpressionOperator != 2)) && Information.IsDate(expression))
                    {
                        expression = "#" + expression + "#";
                    }
                    else if ((row.ExpressionOperator != 2) && !Information.IsNumeric(expression))
                    {
                        expression = "'" + expression + "'";
                    }
                    try
                    {
                        switch (row.ExpressionOperator)
                        {
                            case 1:
                                rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText = ", expression }));
                                goto Label_02FD;

                            case 3:
                                rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText > ", expression }));
                                goto Label_02FD;

                            case 4:
                                rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText < ", expression }));
                                goto Label_02FD;
                        }
                        rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText like '%", expression, "%'" }));
                    }
                    catch (EvaluateException)
                    {
                    }
                }
                else if (!row.IsAnswerIdNull())
                {
                    rowArray = voterAnswers.VotersAnswers.Select("AnswerId=" + row.AnswerId);
                }
                else if (row.IsAnswerIdNull())
                {
                    rowArray = voterAnswers.VotersAnswers.Select("QuestionId=" + row.QuestionId);
                }
                else
                {
                    rowArray = null;
                }
            Label_02FD:
                if ((((rowArray != null) && (row.ConditionalOperator == 1)) && (rowArray.Length > 0)) || ((row.ConditionalOperator == 2) && (rowArray.Length == 0)))
                {
                    return true;
                }
            }
            return false;
        }
		protected string FormatRule(object messageConditionalOperator, object conditionalOperator, 
			string questionText, string answerText, string textFilter, string thanksMessage, 
			string scoreText, string scoreMaxText, object expressionCondition)
		{
			MessageConditionalOperator messageCondition = (MessageConditionalOperator) int.Parse(messageConditionalOperator.ToString());
			thanksMessage = new Questions().ParseHTMLTagsFromQuestionText(thanksMessage,40);
			
			if (messageCondition == MessageConditionalOperator.QuestionAnswer)
			{
				ConditionalOperator condition = (ConditionalOperator)conditionalOperator;
				questionText = new Questions().ParseHTMLTagsFromQuestionText(questionText,40);

				if (condition == ConditionalOperator.ScoredLess)
				{
					return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionScoreLess"),
						thanksMessage,
						scoreText,
						questionText);
				}
				else if (condition == ConditionalOperator.ScoreGreater)
				{
					return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionScoreGreater"),
						thanksMessage,
						scoreText,
						questionText);
				}
				else if (condition == ConditionalOperator.ScoreRange)
				{
					return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionScoreRange"),
						thanksMessage,
						scoreText,
						scoreMaxText,
						questionText);
				}
				else if (condition == ConditionalOperator.ScoreEquals)
				{
					return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionScoreEqual"),
						thanksMessage,
						scoreText,
						questionText);
				}
				else
				{
					if (answerText.Length == 0)
					{
						if (condition == ConditionalOperator.Equal)
						{
							return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionNoAnswer"),
								thanksMessage,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")));
						}
						else
						{
							return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionNoAnswerNot"),
								thanksMessage,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")));
						}
					}
					else if (textFilter.Length == 0)
					{
						if (condition == ConditionalOperator.Equal)
						{
							return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionAnswer"),
								thanksMessage,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")));
						}
						else
						{
							return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionAnswerNot"),
								thanksMessage,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")));
						}
					}
					else 
					{
						string conditionText;
						ExpressionConditionalOperator conditionOperator = ExpressionConditionalOperator.Contains;
						if (expressionCondition.ToString().Length > 0)
						{
							conditionOperator = (ExpressionConditionalOperator) expressionCondition;
						}

						switch (conditionOperator)
						{
							case ExpressionConditionalOperator.Equals :
							{
								conditionText = (((PageBase)Page).GetPageResource("EqualsOperator")).ToLower();
								break;
							}
							case ExpressionConditionalOperator.GreaterThan :
							{
								conditionText = (((PageBase)Page).GetPageResource("GreaterThanOperator")).ToLower();
								break;
							}
							case ExpressionConditionalOperator.LessThan:
							{
								conditionText = (((PageBase)Page).GetPageResource("LessThanOperator")).ToLower();
								break;
							}
							default :
							{
								conditionText = (((PageBase)Page).GetPageResource("ContainsOperator")).ToLower();
								break;
							}
						}

						if (condition == ConditionalOperator.Equal)
						{
							return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionAnswerWithText"),
								thanksMessage,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
								conditionText,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(textFilter, "<[^>]*>", " ")));
						}
						else
						{
							return string.Format(((PageBase)Page).GetPageResource("MessageConditionQuestionAnswerWithTextNot"),
								thanksMessage,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
								conditionText,
								Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(textFilter, "<[^>]*>", " ")));
						}
					}
				}
			}
			else if (messageCondition == MessageConditionalOperator.ScoredLess)
			{
				return string.Format(((PageBase)Page).GetPageResource("MessageConditionScoreLess"),
					thanksMessage,
					scoreText);
			}
			else if (messageCondition == MessageConditionalOperator.ScoreEquals)
			{
				return string.Format(((PageBase)Page).GetPageResource("MessageConditionScoreEqual"),
					thanksMessage,
					scoreText);
			}
			else if (messageCondition == MessageConditionalOperator.ScoreGreater)
			{
				return string.Format(((PageBase)Page).GetPageResource("MessageConditionScoreGreater"),
					thanksMessage,
					scoreText);
			}
			else if (messageCondition == MessageConditionalOperator.ScoreRange)
			{
				return string.Format(((PageBase)Page).GetPageResource("MessageConditionScoreRange"),
					thanksMessage,
					scoreText,
					scoreMaxText);
			}
			else
			{
				return null;
			}
		}
        /// <summary>
        /// Set the forms to match DB question options
        /// </summary>
        private void SetQuestionOptions()
        {
            // Retrieve the original question values
            _question = new Questions().GetQuestionById(_questionId, null);
            QuestionData.QuestionsRow questionRow = _question.Questions[0];

            // Can the question have answers
            if (!(((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.Answerable) > 0) ||
                (((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.ChildQuestion) > 0)
                )
            {
                AnswersDataGrid.Visible = false;
                AddNewAnswerButton.Visible = false;
                AnswerOption.Visible = false;
                MessageLabel.Visible = true;
                ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("SingleQuestionCannotBeEditedMessage"));
            }
            else
            {
                MultipleSelection = ((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.MultipleAnswers) > 0;
                _ratingEnabled = questionRow.RatingEnabled;
                _scoreEnabled = _question.Questions[0].IsSurveyIdNull() ? true :
                        new Surveys().IsSurveyScored(SurveyId);

                AnswersDataGrid.Columns[4].Visible = _ratingEnabled;
                AnswersDataGrid.Columns[5].Visible = _scoreEnabled;
            }
        }
        /// <summary>
        /// Set to section ui state in the correct
        /// state based on the current selected section 
        /// repeat mode
        /// </summary>
        private void SetSectionUiState()
        {
            if (int.Parse(RepeatModeDropdownlist.SelectedValue) == (int)RepeatableSectionMode.FullAnswers)
            {
                UpdateRepeatSectionLabel.Visible = false;
                UpdateSectionLinkTextBox.Visible = false;
                DeleteRepeatSectionLabel.Visible = true;
                MaxSectionAllowedLabel.Visible = true;
                MaxSectionAllowedDropdownlist.Visible = true;
                AddRepeatSectionLabel.Visible = true;
                AddSectionLinkTextBox.Visible = true;
                DeleteSectionLinkTextBox.Visible = true;
                GridAnswersLabel.Visible = false;
                GridAnswersListBox.Visible = false;
                AnswersListBox.Visible = false;
                GridAnswersChoiceLabel.Visible = false;
                EditSectionLinkTextBox.Visible = false;
                EditRepeatSectionLabel.Visible = false;

            }
            else if (int.Parse(RepeatModeDropdownlist.SelectedValue) == (int)RepeatableSectionMode.GridAnswers)
            {
                UpdateRepeatSectionLabel.Visible = true;
                DeleteRepeatSectionLabel.Visible = true;
                AddRepeatSectionLabel.Visible = true;
                AddSectionLinkTextBox.Visible = true;
                UpdateSectionLinkTextBox.Visible = true;
                DeleteSectionLinkTextBox.Visible = true;
                GridAnswersLabel.Visible = true;
                GridAnswersListBox.Visible = true;
                AnswersListBox.Visible = true;
                GridAnswersChoiceLabel.Visible = true;
                EditSectionLinkTextBox.Visible = true;
                EditRepeatSectionLabel.Visible = true;
                MaxSectionAllowedLabel.Visible = true;
                MaxSectionAllowedDropdownlist.Visible = true;


                AnswersListBox.DataSource = new Answers().GetAnswersList(_questionId);
                AnswersListBox.DataMember = "Answers";
                AnswersListBox.DataTextField = "AnswerText";
                AnswersListBox.DataValueField = "AnswerId";
                AnswersListBox.DataBind();

                int[] gridAnswers = new Questions().GetQuestionSectionGridAnswers(_questionId);
                for (int i = 0; i < gridAnswers.Length; i++)
                {
                    ListItem answerItem = AnswersListBox.Items.FindByValue(gridAnswers[i].ToString());
                    if (answerItem != null)
                    {
                        GridAnswersListBox.Items.Add(new ListItem(answerItem.Text, answerItem.Value));
                        AnswersListBox.Items.Remove(answerItem);
                    }
                }
            }
            else
            {
                EditRepeatSectionLabel.Visible = false;
                UpdateRepeatSectionLabel.Visible = false;
                DeleteRepeatSectionLabel.Visible = false;
                AddRepeatSectionLabel.Visible = false;
                AddSectionLinkTextBox.Visible = false;
                UpdateSectionLinkTextBox.Visible = false;
                DeleteSectionLinkTextBox.Visible = false;
                EditSectionLinkTextBox.Visible = false;
                GridAnswersLabel.Visible = false;
                GridAnswersListBox.Visible = false;
                AnswersListBox.Visible = false;
                GridAnswersChoiceLabel.Visible = false;
                MaxSectionAllowedLabel.Visible = false;
                MaxSectionAllowedDropdownlist.Visible = false;
            }
        }
        /// <summary>
        /// Set the forms to match DB question options
        /// </summary>
        private void BindQuestionSectionOptions()
        {
            QuestionSectionOptionData sectionOptions = new Questions().GetQuestionSectionOptions(_questionId, LanguagesDropdownlist.SelectedValue);
            if (sectionOptions.QuestionSectionOptions.Rows.Count > 0)
            {
                RepeatModeDropdownlist.SelectedValue = sectionOptions.QuestionSectionOptions[0].RepeatableSectionModeId.ToString();
                MaxSectionAllowedDropdownlist.SelectedValue = sectionOptions.QuestionSectionOptions[0].MaxSections.ToString();
                AddSectionLinkTextBox.Text = sectionOptions.QuestionSectionOptions[0].AddSectionLinkText;
                DeleteSectionLinkTextBox.Text = sectionOptions.QuestionSectionOptions[0].DeleteSectionLinkText;
                UpdateSectionLinkTextBox.Text = sectionOptions.QuestionSectionOptions[0].UpdateSectionLinkText;
                EditSectionLinkTextBox.Text = sectionOptions.QuestionSectionOptions[0].EditSectionLinkText;
            }

            SetSectionUiState();
        }
        /// <summary>
        /// Set the forms to match DB question options
        /// </summary>
        private void BindQuestionOptions()
        {
            // Retrieve the original question values
            QuestionData question = new Questions().GetQuestionById(_questionId, LanguagesDropdownlist.SelectedValue);
            QuestionData.QuestionsRow questionRow = question.Questions[0];

            QuestionExtraLinks1.Initialize(questionRow.SurveyId, questionRow.QuestionId, questionRow.DisplayOrder, questionRow.PageNumber);
 
            // Assign them to the form
            QuestionFreeTextBox.Text = questionRow.QuestionText;
            txtQuestionID.Text = questionRow.QuestionIdText;
            DisplayModeDropDownList.SelectedValue =
                (questionRow.IsLayoutModeIdNull()) ? ((int)QuestionLayoutMode.Horizontal).ToString() : questionRow.LayoutModeId.ToString();
            ColumnDropdownlist.SelectedValue = questionRow.ColumnsNumber.ToString();
            SelectionModeDropDownList.SelectedValue = questionRow.SelectionModeId.ToString();
            MinSelectionDropDownList.SelectedValue =
                (questionRow.IsMinSelectionRequiredNull()) ? "0" : questionRow.MinSelectionRequired.ToString();
            MaxAllowedDropDownList.SelectedValue =
                (questionRow.IsMaxSelectionAllowedNull()) ? "0" : questionRow.MaxSelectionAllowed.ToString();

             //JL: Enable or disable the Min Max dropdown list depending on selectionmodedropdownlist option selected by user
             EnableDisableMinMaxDropDownList(); 

            RandomizeCheckBox.Checked = questionRow.RandomizeAnswers;
            RatingCheckbox.Checked = questionRow.RatingEnabled;

            RatingCheckbox.Checked = questionRow.RatingEnabled;

            EnableDisableGroupFields(RatingCheckbox.Checked);
            BindQuestionGroups();

            PipeAliasTextBox.Text = questionRow.QuestionPipeAlias;
            RandomizeCheckBox.Enabled = !RatingCheckbox.Checked;

            ViewState["LibraryId"] = questionRow.IsLibraryIdNull() ? -1 : questionRow.LibraryId;
            if (!questionRow.IsLibraryIdNull() && !NSurveyUser.Identity.IsAdmin)
            {
                CheckRight(NSurveyRights.ManageLibrary, true);
            }

            // Can the question have answers
            if (((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.Answerable) > 0)
            {
                AnswerOptionsPlaceholder.Visible = true;
                RepeatSectionOptionPlaceHolder.Visible = true;
                EditAnswersButton.Enabled = true;
                MultipleSelection = ((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.MultipleAnswers) > 0;
            }
            else
            {
                RepeatSectionOptionPlaceHolder.Visible = false;
                AnswerOptionsPlaceholder.Visible = false;
                EditAnswersButton.Enabled = false;
                new Question().DeleteQuestionSectionOptions(_questionId);
            }

            if (questionRow.RatingEnabled)
                BindQuestionGroups();
            else
            {
                ddlGroup.Enabled = true;
                ddlSubGroup.Enabled = true;
            }

            txtAlias.Text = questionRow.Alias;
            txtHelpText.Text = questionRow.HelpText;
            chbShowHelpText.Checked = (questionRow.ShowHelpText) ? (bool)questionRow.ShowHelpText : false;
        }
		/// <summary>
		/// Get the current DB stats and fill 
		/// the label with them
		/// </summary>
		private void BindData()
		{
			isScored = new Surveys().IsSurveyScored(SurveyId);

			TimeSpan timeTaken;
			_voterAnswers = new Voters().GetVoterAnswers(_voterId);

			if (!_voterAnswers.Voters[0].IsVoteDateNull() && !_voterAnswers.Voters[0].IsStartDateNull())
			{
				timeTaken = _voterAnswers.Voters[0].VoteDate - _voterAnswers.Voters[0].StartDate;
			}
			else
			{
				timeTaken = new TimeSpan(0);
			}

			VoterUIDLabel.Text = _voterId.ToString();
			IPAddressLabel.Text = _voterAnswers.Voters[0].IPSource;
			VoteDateLabel.Text = _voterAnswers.Voters[0].VoteDate.ToString();
			VoterEmail.Text = _voterAnswers.Voters[0].IsEmailNull() ? GetPageResource("AnonymousVoteInfo") : _voterAnswers.Voters[0].Email;
			VoterUserName.Text = _voterAnswers.Voters[0].IsContextUserNameNull() ?  GetPageResource("ContextUserNameDisabled") : _voterAnswers.Voters[0].ContextUserName;
			VoterLanguageValueLabel.Text = _voterAnswers.Voters[0].IsLanguageCodeNull() || _voterAnswers.Voters[0].LanguageCode.Length == 0 ?  
				GetPageResource("LanguageUndefined") : _voterAnswers.Voters[0].LanguageCode;
			TimeToTakeSurveyLabel.Text = string.Format("{0} {1}, {2} secs.", timeTaken.Minutes.ToString(), GetPageResource("MinutesInfo"), timeTaken.Seconds.ToString());

			WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState, null);
			NameValueCollection addInVoterData;
			for (int i=0;i<securityAddIns.Count;i++)
			{
				addInVoterData = securityAddIns[i].GetAddInVoterData(_voterId);
				if (addInVoterData != null)
				{
					// Creates a new addin voter details page
					SecurityAddInVoterReportControl addInVoterControl = 
						(SecurityAddInVoterReportControl)LoadControl("UserControls/SecurityAddInVoterReportControl.ascx");

					addInVoterControl.AddInDescription = securityAddIns[i].Description;
					addInVoterControl.AddInVoterData = addInVoterData;
					AddInVoterDataPlaceHolder.Controls.Add(addInVoterControl);
				}
			}

			_questionData = new Questions().GetQuestionHierarchy(SurveyId);
			QuestionsDataGrid.DataSource = GetParentQuestions();
			QuestionsDataGrid.DataKeyField = "QuestionId";
			QuestionsDataGrid.DataBind();
			if (isScored)
			{
				VoterScoreTotalLabel.Text = GetPageResource("VoterScoreTotalLabel") + _totalScore.ToString();
			}
		}
		private TableRow GenerateNotAnsweredRow(int compareQuestionId, int baseQuestionId, DataSet totalCountData)
		{
			TableRow baseRow = new TableRow();
			TableCell baseCell = new TableCell();
			baseCell.Wrap = false;
			baseCell.CssClass = "crossTabBaseCell";
			baseCell.Text = GetPageResource("CrossTabNotAnsweredMessage");
			baseRow.Cells.Add(baseCell);

			DataSet crossTabStats = new Questions().GetUnansweredCrossTabResults(compareQuestionId, baseQuestionId);

			for (int i=0;i<crossTabStats.Tables[0].Rows.Count;i++)
			{
				baseCell = new TableCell();
				baseCell.Wrap = false;

				double columnTotal = Convert.ToDouble(totalCountData.Tables[0].Rows[i].ItemArray[0]);
				double voterTotal = Convert.ToDouble(crossTabStats.Tables[0].Rows[i].ItemArray[0]);
				if (voterTotal > 0 && columnTotal>0)
				{
					baseCell.Text = string.Format("{0}% ({1})", ((voterTotal/columnTotal)*100).ToString("##.##"), voterTotal);
				}
				else
				{
					baseCell.Text = "0% (0)";
				}

				baseRow.Cells.Add(baseCell);
			}

			return baseRow;
		}
		protected void HideFields(bool hideConditions, bool hideAnswers, bool hideTextBox, 
			bool hideScore, bool hideScoreRange, bool rebindLogic, bool hideQuestion)
		{
			QuestionFilterDropdownlist.Visible = !hideQuestion;
			QuestionLabel.Visible = !hideQuestion;
			ScoreLabel.Visible = !hideScore;
			ScoreTextbox.Visible  = !hideScore;
			ScoreRangeLabel.Visible = !hideScoreRange;
			ScoreMaxTextbox.Visible = !hideScoreRange;
			ConditionalLabel.Visible = !hideConditions;
			LogicDropDownList.Visible = !hideConditions;
			AnswerLabel.Visible = !hideAnswers;
			AnswerFilterDropdownlist.Visible = !hideAnswers;
			TextFilterTextbox.Visible = false;
			FilterTextLabel.Visible = false;
			TextFilterTextbox.Text = string.Empty;
            ConditionCKeditor.Visible = !hideTextBox;
			ScoreTagLabel.Visible = _isScored && !hideTextBox;
			ExpressionLogicDropdownlist.Visible = false;
			TextEvaluationConditionLabel.Visible = false;

			ConditionalMessageLabel.Visible = !hideTextBox;

			if (!Page.IsPostBack || rebindLogic)
			{
				LogicDropDownList.Items.Clear();
				LogicDropDownList.Items.Add(new ListItem(GetPageResource("AnsweredConditionOption"), "1"));
				LogicDropDownList.Items.Add(new ListItem(GetPageResource("NotAnsweredConditionOption"), "2"));
				if (new Surveys().IsSurveyScored(SurveyId))
				{
					bool showScoreOptions = true;
					if (QuestionFilterDropdownlist.SelectedValue != "-1")
					{
						// Check if the question is a matrix type
						// currently matrix type interface doesnt support
						// setting scores
						QuestionData question = new Questions().GetQuestionById(int.Parse(QuestionFilterDropdownlist.SelectedValue), null);
						if (question.Questions.Rows.Count > 0 && 
							((QuestionTypeMode)question.Questions[0].TypeMode & QuestionTypeMode.ChildQuestion)>0)
							showScoreOptions = false;
					}

					if (showScoreOptions && _isScored)
					{
						LogicDropDownList.Items.Add(new ListItem(GetPageResource("ScoredEqualConditionOption"), "3"));
						LogicDropDownList.Items.Add(new ListItem(GetPageResource("ScoredLessConditionOption"), "4"));
						LogicDropDownList.Items.Add(new ListItem(GetPageResource("ScoredGreaterConditionOption"), "5"));
						LogicDropDownList.Items.Add(new ListItem(GetPageResource("ScoredRangeConditionOperator"), "6"));
					}
				}
			}

		}
		void BuildCrossTabTabe()
		{
			AnswerData 
				baseAnswers = new Answers().GetSelectableAnswers(int.Parse(BaseQuestionDropDownList.SelectedValue)),
				compareAnswers = new Answers().GetSelectableAnswers(int.Parse(CompareQuestionDropDownList.SelectedValue));

			int compareQuestionId = int.Parse(CompareQuestionDropDownList.SelectedValue),
				baseQuestionId = int.Parse(BaseQuestionDropDownList.SelectedValue);

			DataSet totalCountData = new Questions().GetTotalCrossTabResults(compareQuestionId, baseQuestionId);


			Table crossTable = new Table();
			crossTable.CssClass = "crossTabTable";

			crossTable.Rows.Add(GenerateTableHeader(compareAnswers));

			crossTable.Rows.Add(GenerateNotAnsweredRow(compareQuestionId, baseQuestionId, totalCountData));

			foreach (AnswerData.AnswersRow answer in baseAnswers.Answers.Rows)
			{
				crossTable.Rows.Add(GenerateBaseRow(answer, compareQuestionId, totalCountData));
			}

			if (totalCountData.Tables.Count > 0)
			{
				TableRow breakRow= new TableRow();
				TableCell breakCell = new TableCell();
				breakCell.ColumnSpan = totalCountData.Tables[0].Rows.Count + 1;
                breakCell.Text = "&nbsp;";
				breakRow.Cells.Add(breakCell);
				crossTable.Rows.Add(breakRow);
			}

			crossTable.Rows.Add(GenerateTotalRow(totalCountData));
				
			CrossTabResultsPlaceHolder.Controls.Add(crossTable);
		}
        /// <summary>
        /// Builds the HTML to show the survey box
        /// </summary>
        protected virtual void BuildSurveyBox(bool enableQuestionDefaults)
        {
            QuestionData data;
            this._questions = new QuestionItemCollection();
            this._questionContainer = Votations.NSurvey.BE.Votations.NSurvey.Constants.Commons.GetCentPercentTable();//JJ;
            this._questionContainer.Rows.Add(this.BuildRow("", null));
            this._questionContainer.Rows[0].EnableViewState = false;
            this._questionContainer.Rows.Add(this.BuildRow("", null));
            this._questionContainer.Rows[1].EnableViewState = false;
            this._questionContainer.Width = Unit.Percentage(100.0);
            // moved to css
            //            this._questionContainer.CellSpacing = 0;
            //            this._questionContainer.CellPadding = 3;



            Votations.NSurvey.SQLServerDAL.SurveyLayout u = new Votations.NSurvey.SQLServerDAL.SurveyLayout();
            var _userSettings = u.SurveyLayoutGet(this.SurveyId, this.LanguageCode);


            if (!(_userSettings == null || _userSettings.SurveyLayout.Count == 0))
            {
                this.Controls.Add(BuildCustomHeaderOrFooter(HttpUtility.HtmlDecode(_userSettings.SurveyLayout[0].SurveyHeaderText)));
            }
            this._questionContainer.ControlStyle.Font.CopyFrom(base.ControlStyle.Font);
            this.Controls.Add(this._questionContainer);
            PageOptionData surveyPageOptions = new Surveys().GetSurveyPageOptions(this.SurveyId, this.CurrentPageIndex);
            if (surveyPageOptions.PageOptions.Rows.Count > 0)
            {
                this._enableSubmitButton = surveyPageOptions.PageOptions[0].EnableSubmitButton;
                this._randomQuestions = surveyPageOptions.PageOptions[0].RandomizeQuestions;
            }
            if (this._randomQuestions)
            {
                data = new Questions().GetRandomPagedQuestions(this.SurveyId, this.CurrentPageIndex, this.GetRandomSeedForQuestion(), this.LanguageCode);
            }
            else
            {
                data = new Questions().GetPagedQuestions(this.SurveyId, this.CurrentPageIndex, this.LanguageCode);
            }
            foreach (QuestionData.QuestionsRow row2 in data.Questions.Rows)
            {
                if (!new Question().SkipQuestion(row2.QuestionId, this.VoterAnswers, this._isScored))
                {
                    TableRow row = new TableRow();
                    TableCell cell = new TableCell();
                    row.Cells.Add(cell);

                    this._questionContainer.Rows.Add(row);
                    this.InsertQuestion(row2, cell, enableQuestionDefaults);
                }
                else
                {
                    this.CleanVoterQuestionAnswers(QuestionItemFactory.Create(row2, null, this.UniqueID, this.GetRandomSeedForQuestion(), (VoterAnswersData.VotersAnswersDataTable)this.VoterAnswers.VotersAnswers.Copy(), enableQuestionDefaults));
                }
            }
            if (this._enableNavigation && this._previousQuestionNumbering)
            {
                this.ReverseQuestionsNumbers();
            }
            if ((this.CurrentPageIndex < this.TotalPageNumber) && !this._enableSubmitButton)
            {
                this._questionContainer.Rows.Add(this.BuildNextPageButtonRow());
            }
            else
            {
                this._questionContainer.Rows.Add(this.BuildSubmitButtonRow());
            }

            if (!(_userSettings == null || _userSettings.SurveyLayout.Count == 0))
            {
                this.Controls.Add(BuildCustomHeaderOrFooter(HttpUtility.HtmlDecode(_userSettings.SurveyLayout[0].SurveyFooterText)));
            }
            this.ViewState["SubmitButtonUID"] = this._submitButton.UniqueID;
        }
        int GenerateFilter()
        {
            int questionId = Convert.ToInt32(ddlAutoQuestions.SelectedValue);
            if (questionId == -1) return 0;
            var q = new Questions().GetAnswerableQuestionList(SurveyId).Questions.Single(x => x.QuestionId == questionId);
            var parentFilterId = Convert.ToInt32(ddlAutoFilterParent.SelectedValue);
            FilterData.FiltersRow p = parentFilterId == 0
                ? new Filters().GetEmptyFilter().Filters.FindByFilterId(parentFilterId)
                : new Filters().GetFilterById(parentFilterId).Filters.FindByFilterId(parentFilterId);
            int filterCount = 0;

            foreach (AnswerData.AnswersRow a in new Answers().GetAnswersList(questionId).Answers)
            {

                if (((AnswerTypeEnum)a.AnswerTypeId) == AnswerTypeEnum.SelectionTextType)
                {
                    AddFilter(q, a, p);
                    filterCount++;
                }
            }
            return filterCount;
        }
		private void BuildTemplateList()
		{
            TemplatesPlaceHolder.Controls.Clear();
			_questionsData = new Questions().GetLibraryQuestions(_libraryId,LanguagesDropdownlist.SelectedValue);	
			
			foreach (QuestionData.QuestionsRow question in _questionsData.Questions.Rows)
			{
				Table questionsContainer = new Table();
				questionsContainer.Width = Unit.Percentage(100);
				Table questionTable = new Table();
				questionTable.CellSpacing = 2;
				questionTable.CellPadding = 4;
				questionTable.CssClass = "questionBuilder";
				AddQuestionWebControl(questionTable, question);
                questionsContainer.Rows.Add(BuildRow(questionTable, ""));
				TemplatesPlaceHolder.Controls.Add(questionsContainer);
			}

		}
        private void LibraryDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (SurveyListDropdownlist.SelectedValue == "-1")
            {
                LibraryQuestionsDropDownList.Visible = false;
                LibraryQuestionsDropDownList.Items.Clear();
                CopyExistingQuestionButton.Enabled = false;
            }
            else
            {
                LibraryQuestionsDropDownList.Visible = true;

                QuestionData questions = new Questions().GetLibraryQuestionListWithoutChilds(int.Parse(LibraryDropDownList.SelectedValue));
                if (questions.Questions.Rows.Count > 0)
                {
                    LibraryQuestionsDropDownList.DataSource = questions;
                    LibraryQuestionsDropDownList.DataMember = "questions";
                    LibraryQuestionsDropDownList.DataTextField = "questionText";
                    LibraryQuestionsDropDownList.DataValueField = "questionid";
                    LibraryQuestionsDropDownList.DataBind();
                    CopyExistingQuestionButton.Enabled = true;
                }
                else
                {
                    LibraryQuestionsDropDownList.Items.Clear();
                    LibraryQuestionsDropDownList.Items.Insert(0, new ListItem(GetPageResource("NoQuestionToCopyAvailableMessage"), "-1"));
                }
            }
        }
        /// <summary>
        /// Set the forms to match DB question options
        /// </summary>
        private void BindQuestionOptions()
        {
            // Retrieve the original question values
            QuestionData question = new Questions().GetQuestionById(_parentQuestionId, LanguagesDropdownlist.SelectedValue);
            QuestionData.QuestionsRow questionRow = question.Questions[0];
            QuestionExtraLinks1.Initialize(questionRow.SurveyId, questionRow.QuestionId, questionRow.DisplayOrder, questionRow.PageNumber);
            // 
            // Assign them to the form
            QuestionFreeTextBox.Text = questionRow.QuestionText;
            MinSelectionDropDownList.SelectedValue =
                (questionRow.IsMinSelectionRequiredNull()) ? "0" : questionRow.MinSelectionRequired.ToString();
            MaxAllowedDropDownList.SelectedValue =
                (questionRow.IsMaxSelectionAllowedNull()) ? "0" : questionRow.MaxSelectionAllowed.ToString();

            MultipleChoiceCheckbox.Checked = questionRow.SelectionModeId == (int)QuestionSelectionMode.MultiMatrix;
            RatingCheckbox.Checked = questionRow.RatingEnabled;
            ViewState["LibrayID"] = questionRow.IsLibraryIdNull() ? -1 : questionRow.LibraryId;

            if (!questionRow.IsLibraryIdNull() && !NSurveyUser.Identity.IsAdmin)
            {
                CheckRight(NSurveyRights.ManageLibrary, true);
            }

            QuestionSectionOptionData sectionOptions = new Questions().GetQuestionSectionOptions(_parentQuestionId, LanguagesDropdownlist.SelectedValue);
            if (sectionOptions.QuestionSectionOptions.Rows.Count > 0)
            {

                RepeatSectionCheckbox.Checked = true;
                RepeatSectionOptionPlaceholder.Visible = true;
                AddSectionLinkTextBox.Text = sectionOptions.QuestionSectionOptions[0].AddSectionLinkText;
                DeleteSectionLinkTextBox.Text = sectionOptions.QuestionSectionOptions[0].DeleteSectionLinkText;
            }
            else
            {
                RepeatSectionCheckbox.Checked = false;
                RepeatSectionOptionPlaceholder.Visible = false;


            }


            RatingCheckbox.Checked = questionRow.RatingEnabled;

            EnableDisableGroupFields(RatingCheckbox.Checked);
            BindQuestionGroups();

            txtQuestionID.Text = questionRow.QuestionIdText;
            txtAlias.Text = questionRow.Alias;
            txtHelpText.Text = questionRow.HelpText;
            chbShowHelpText.Checked = (questionRow.ShowHelpText != null) ? (bool)questionRow.ShowHelpText : false;
        }
        /// <summary>
        /// Builds the Question list table with
        /// the edit options
        /// </summary>
        private void BuildQuestionList()
        {
            _questionsData = new Questions().GetQuestions(SurveyId, LanguagesDropdownlist.SelectedValue);
            int currentPage = 1,
                previousDisplayOrder = 0,
                totalPages = new Surveys().GetPagesNumber(SurveyId);

            Table questionsContainer = new Table();
            questionsContainer.Width = Unit.Percentage(100);
            Table questionTable = new Table();
            // moved to css file
            // questionTable.CellSpacing = 2;
            // questionTable.CellPadding = 4;
            questionTable.CssClass = "questionBuilder";

            TableRow pageBreakRow = BuildRow(null);

            // always add first page 
            questionTable.Rows.Add(pageBreakRow);

            foreach (QuestionData.QuestionsRow question in _questionsData.Questions.Rows)
            {
                while (question.PageNumber > currentPage)
                {
                    var lastq = _questionsData.Questions
                        .AsEnumerable().Where(x => x.PageNumber < currentPage)
                        .OrderByDescending(x => x.DisplayOrder).FirstOrDefault();
                    int displayOrder = lastq == null ? 0 : lastq.DisplayOrder + 1;
                    pageBreakRow.Cells[0].Controls.Add(BuildPageBreakOptionsRow(currentPage, totalPages, displayOrder));

                    currentPage++;
                    questionsContainer.Rows.Add(BuildRow(questionTable));
                    QuestionListPlaceHolder.Controls.Add(questionsContainer);

                    // Creates a new page
                    questionsContainer = new Table();
                    questionsContainer.Width = Unit.Percentage(100);
                    questionTable = new Table();
                    // moved to css file:
                    // questionTable.CellSpacing = 2;
                    // questionTable.CellPadding = 4;
                    questionTable.CssClass = "questionBuilder";

                    pageBreakRow = BuildRow(null);
                    questionTable.Rows.Add(pageBreakRow);
                }

                if (question.PageNumber == currentPage)
                {
                    AddQuestionWebControl(questionTable, question);
                    previousDisplayOrder = question.DisplayOrder;
                }
            }

            pageBreakRow.Cells[0].Controls.Add(BuildPageBreakOptionsRow(currentPage, totalPages, previousDisplayOrder));

            questionsContainer.Rows.Add(BuildRow(questionTable));
            QuestionListPlaceHolder.Controls.Add(questionsContainer);
        }
        private void BindQuestionGroups()
        {
            QuestionData question = new Questions().GetQuestionById(_parentQuestionId, LanguagesDropdownlist.SelectedValue);
            QuestionData.QuestionsRow questionRow = question.Questions[0];
            int questionGroupId = questionRow.IsQuestionGroupIDNull() ? -1 : (int)questionRow.QuestionGroupID;

            int selectedQuestionGroupId = -1;

            QuestionGroupsData data = new Votations.NSurvey.DataAccess.QuestionGroups().GetAll(LanguagesDropdownlist.SelectedValue);
            DataView groupView = data.DefaultViewManager.CreateDataView(data.Tables[0]);
            DataView subGroupView = data.DefaultViewManager.CreateDataView(data.Tables[0]);
            groupView.RowFilter = "ParentGroupId is null";


            foreach (QuestionGroupsData.QuestionGroupsRow row in data.Tables[0].Rows)
            {
                if (row.ID == questionGroupId)
                {
                    selectedQuestionGroupId = (row.ParentGroupID != null) ? (int)row.ParentGroupID : questionGroupId;
                    break;
                }
            }


            if (ddlGroup.SelectedIndex > -1 && ddlGroup.SelectedValue != selectedQuestionGroupId.ToString())
                selectedQuestionGroupId = int.Parse(ddlGroup.SelectedValue);

            subGroupView.RowFilter = "ParentGroupId = " + selectedQuestionGroupId;
            ddlGroup.Items.Clear();
            ddlGroup.Items.Add(new ListItem("-Select-", "-1"));
            ddlSubGroup.Items.Clear();
            ddlSubGroup.Items.Add(new ListItem("-Select-", "-1"));

            ddlGroup.DataSource = groupView;
            ddlGroup.DataTextField = "GroupName";
            ddlGroup.DataValueField = "ID";
            ddlGroup.DataBind();

            ddlSubGroup.DataSource = subGroupView;
            ddlSubGroup.DataTextField = "GroupName";
            ddlSubGroup.DataValueField = "ID";
            ddlSubGroup.DataBind();

            foreach (ListItem item in ddlGroup.Items)
            {
                if (item.Value == selectedQuestionGroupId.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }

            foreach (ListItem item in ddlSubGroup.Items)
            {
                if (item.Value == questionGroupId.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }
        }
		protected void SetQuestionData(ChartEngine engine, PieChart pieChart)
		{
			try
			{
				DateTime startDate = Information.IsDate(Request["StartDate"]) ?
					DateTime.Parse(Request["StartDate"]) : new DateTime(1900,1,1),
					endDate = Information.IsDate(Request["EndDate"]) ?
					DateTime.Parse(Request["EndDate"]) : new DateTime(2100,1,1);

				_dataSource = new Questions().GetQuestionResults(_questionId, _filterId, _sortOrder, 
					Request["LanguageCode"], startDate, endDate);
			}
			catch (QuestionNotFoundException)
			{
				return;
			}

			QuestionResultsData.AnswersRow[] answers = _dataSource.Questions[0].GetAnswersRows();

			// Set-up question text
			engine.Title  = new ChartText();
			engine.Title.ForeColor = Color.FromArgb(255, 255, 255);
			engine.Title.Font = new Font("Tahoma", 9, FontStyle.Bold);

			// Do we need to show the parent question text for matrix based child questions
			if (!_dataSource.Questions[0].IsParentQuestionIdNull() && _dataSource.Questions[0].ParentQuestionText != null) 
			{
				String questionText = String.Format("{0} - {1}", 
					_dataSource.Questions[0].ParentQuestionText, 
					_dataSource.Questions[0].QuestionText);

				// Show parent and child question text
				engine.Title.Text = Server.HtmlDecode(questionText);
			} 
			else 
			{
				// Show question text
				engine.Title.Text = Server.HtmlDecode(_dataSource.Questions[0].QuestionText);
			}

			SetAnswerData(answers, GetVotersTotal(answers), engine, pieChart);
		}
		/// <summary>
		/// Get the current DB stats and build 
		/// the results tables
		/// </summary>
		private void BuildHtmlResults(int questionId)
		{
			QuestionData questionsData;
			if (questionId == 0)
			{
				questionsData = new Questions().GetQuestionListWithSelectableAnswers(SurveyId);
			}
			else
			{
				questionsData = new Questions().GetQuestionById(questionId, null);
			}


			ChartRepeater.Visible = false;
			SingleChartImage.Visible = false;
			
			Table resultsTable = new Table();
			resultsTable.CellSpacing = 10;
			TableCell resultsTableCell = new TableCell();
			TableRow resultsTableRow = new TableRow();

			resultsTable.CssClass = "resultsTable";
			foreach (QuestionData.QuestionsRow question in questionsData.Questions.Rows)
			{
					resultsTableCell = new TableCell();
					resultsTableRow = new TableRow();
					Style questionStyle = new Style();
					Style answerStyle = new Style();
					questionStyle.Font.Bold = true;
					questionStyle.Font.Size = FontUnit.XSmall;
					questionStyle.ForeColor = System.Drawing.Color.Black;
					//questionStyle.BackColor = System.Drawing.Color.FromArgb(225,238,241);
					answerStyle.Font.Size = FontUnit.XXSmall;
					ResultItem questionResults = new ResultItem();
					questionResults.BorderWidth = Unit.Pixel(1);
					questionResults.BorderColor = System.Drawing.Color.FromArgb(123,123,123);
					questionResults.BackColor = System.Drawing.Color.FromArgb(243,243,243);
					questionResults.Width = Unit.Pixel(655);
					questionResults.BarColor = "blueadmin";
					questionResults.QuestionStyle = questionStyle;
					questionResults.AnswerStyle = answerStyle;
					questionResults.FootStyle = answerStyle;
					
					DateTime startDate = Information.IsDate(StartDateTextBox.Text) ?
						DateTime.Parse(StartDateTextBox.Text) : new DateTime(1900,1,1),
						endDate = Information.IsDate(EndDateTextBox.Text) ?
						DateTime.Parse(EndDateTextBox.Text) : new DateTime(2100,1,1);
				
					questionResults.DataSource =new Questions().GetQuestionResults(question.QuestionId,
                        GetFilterId(), ResultsOrderDropDownList.SelectedValue, LanguagesDropdownlist.SelectedValue, startDate, endDate);
					
					questionResults.DataBind();
					resultsTableCell.Controls.Add(questionResults);
					
					resultsTableRow.Cells.Add(resultsTableCell);
					resultsTable.Rows.Add(resultsTableRow);
			}

			ResultsPlaceHolder.Controls.Add(resultsTable);
		}
		protected string FormatRule(object conditionalOperator, string questionText, string answerText, 
			string textFilter, string pageNumber, string scoreText, string scoreMaxText, object expressionCondition)
		{
			ConditionalOperator condition = (ConditionalOperator)conditionalOperator;

			questionText = new Questions().ParseHTMLTagsFromQuestionText(questionText,40);

			if (pageNumber == "-1")
			{
                pageNumber = ((PageBase)Page).GetPageResource("BranchingRuleEndSurvey");
			}
			else
			{
				pageNumber = string.Format(((PageBase)Page).GetPageResource("BranchingRulePage"), pageNumber);
			}
			
			if (condition == ConditionalOperator.ScoredLess)
			{
				return string.Format(((PageBase)Page).GetPageResource("BranchingRuleScoreLess"),
					scoreText,
					questionText,
					pageNumber);
			}
			else if (condition == ConditionalOperator.ScoreGreater)
			{
				return string.Format(((PageBase)Page).GetPageResource("BranchingRuleScoreGreater"),
					scoreText,
					questionText,
					pageNumber);
			}
			else if (condition == ConditionalOperator.ScoreRange)
			{
				return string.Format(((PageBase)Page).GetPageResource("BranchingRuleScoreRange"),
					scoreText,
					scoreMaxText,
					questionText,
					pageNumber);
			}
			else if (condition == ConditionalOperator.ScoreEquals)
			{
				return string.Format(((PageBase)Page).GetPageResource("BranchingRuleScoreEqual"),
					scoreText,
					questionText,
					pageNumber);
			}
			else
			{
				if (answerText.Length == 0)
				{
					if (condition == ConditionalOperator.Equal)
					{
						return string.Format(((PageBase)Page).GetPageResource("BranchingRuleNoAnswer"),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
							pageNumber);
					}
					else
					{
						return string.Format(((PageBase)Page).GetPageResource("BranchingRuleNoAnswerNot"),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
							pageNumber);
					}
				}
				else if (textFilter.Length == 0)
				{
					if (condition == ConditionalOperator.Equal)
					{
						return string.Format(((PageBase)Page).GetPageResource("BranchingRuleAnswer"),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
							pageNumber);
					}
					else
					{
						return string.Format(((PageBase)Page).GetPageResource("BranchingRuleAnswerNot"),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
							pageNumber);
					}
				}
				else 
				{
					string conditionText;
					ExpressionConditionalOperator conditionOperator = ExpressionConditionalOperator.Contains;
					if (expressionCondition.ToString().Length > 0)
					{
						conditionOperator = (ExpressionConditionalOperator) expressionCondition;
					}

					switch (conditionOperator)
					{
						case ExpressionConditionalOperator.Equals :
						{
							conditionText = (((PageBase)Page).GetPageResource("EqualsOperator")).ToLower();
							break;
						}
						case ExpressionConditionalOperator.GreaterThan :
						{
							conditionText = (((PageBase)Page).GetPageResource("GreaterThanOperator")).ToLower();
							break;
						}
						case ExpressionConditionalOperator.LessThan:
						{
							conditionText = (((PageBase)Page).GetPageResource("LessThanOperator")).ToLower();
							break;
						}
						default :
						{
							conditionText = (((PageBase)Page).GetPageResource("ContainsOperator")).ToLower();
							break;
						}
					}

					if (condition == ConditionalOperator.Equal)
					{
						return string.Format(((PageBase)Page).GetPageResource("BranchingRuleAnswerWithText"),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
							conditionText,
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(textFilter, "<[^>]*>", " ")),
							pageNumber);
					}
					else
					{
						return string.Format(((PageBase)Page).GetPageResource("BranchingRuleAnswerWithTextNot"),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(questionText, "<[^>]*>", " ")),
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(answerText, "<[^>]*>", " ")),
							conditionText,
							Server.HtmlEncode(System.Text.RegularExpressions.Regex.Replace(textFilter, "<[^>]*>", " ")),
							pageNumber);
					}
				}
			}
		}