/// <summary>
		/// Builds the QuestionSearchCriteria. Used both from Search Button and from Service
		/// </summary>
		public static AddendumSearchCriteriaV2 BuildSearchCriteriaObject(ThinkgateUser user, CriteriaController criteriaController, string requestedSortField = null)
		{

			/* Sort */
			string sortField = null;
			NameValue nvSortField = SortFields().Find(x => x.Name == requestedSortField);   // ensure that the user given value for sort is in the defined list of options
			if (nvSortField != null) sortField = nvSortField.Value;

			/* Item Banks - Remove from master list based on filter if given */
			var itemBanks = ItemBankMasterList.GetItemBanksForUser(user);

            if (TestCategory != null && TestCategory == AssessmentCategories.District.ToString())
            {
                for (var rowIndex = itemBanks.Rows.Count - 1; rowIndex >= 0; rowIndex--)
                {
                    if (itemBanks.Rows[rowIndex]["Label"].ToString() == "Personal")
                    { itemBanks.Rows[rowIndex].Delete(); }
                }
            }

            var selectedItemBanks = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("ItemBank").Select(x => x.Text);
			if (selectedItemBanks.Any()) itemBanks.DeleteByLabel(selectedItemBanks);

			/* Text Search */
			string searchText = string.Empty;
			string searchOption = string.Empty;
			var txtSearchList = criteriaController.ParseCriteria<TextWithDropdown.ValueObject>("TextSearch");
			if (txtSearchList.Count > 0)
			{
				// we ensure that the value the user gave us for text search type is a valid option
				var confirmedOption = TextSearchDropdownValues().Find(x => x.Name == txtSearchList[0].Option) ?? TextSearchDropdownValues().First();
				if (!String.IsNullOrEmpty(txtSearchList[0].Text))
				{
					searchText = txtSearchList[0].Text;
					searchOption = confirmedOption.Value;
				}
			}

			/* Courses */
			var selectedGrades = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Grade").Select(x => x.Text).ToList();
			var selectedSubjects = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Subject").Select(x => x.Text).ToList();
			var selectedCourses = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Course").Select(x => x.Text).ToList();
			var selectedStandardSets = new drGeneric_String(criteriaController.ParseCriteria<CheckBoxList.ValueObject>("StandardSet").Select(x => x.Text));     // take straight to drGeneric_String because it's going to SQL
			var filteredCourses = CourseMasterList.GetStandardCoursesForUser(user).FilterByGradesSubjectsStandardSetsAndCourse(selectedGrades, selectedSubjects, selectedStandardSets, selectedCourses);


			/* Type/Genre */
			var selectedAddendumGenres = new drGeneric_String();
			var selectedAddendumTypes = new drGeneric_String();
			var selectedTypesGenres = criteriaController.ParseCriteria<AddendumType.ValueObject>("AddendumType");
			foreach (var selectedTypesGenre in selectedTypesGenres)
			{
				if (selectedTypesGenre.Genre != null)
				{
					selectedAddendumGenres.Add(selectedTypesGenre.Genre);
				}
				else
				{
					selectedAddendumTypes.Add(selectedTypesGenre.Text);
				}
			}
			if (selectedAddendumGenres.Count > 0)
				selectedAddendumTypes.Add("Passage");


		    var selectedExpirationStatus = criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault() != null ? 
                criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault().Value : "I";
            if (!ShowExpiredItems)
            {
                selectedExpirationStatus = "E";

            }
            drGeneric_String_String selectedExpirationDateRange = new drGeneric_String_String();
            foreach (var val in criteriaController.ParseCriteria<DateRange.ValueObject>("ExpirationDateRange"))
            {
                selectedExpirationDateRange.Add(val.Type == "Start" ? "CreatedDateStart" : "CreatedDateEnd", val.Date);
            }


			/* Build Criteria Object */
            var asc = new AddendumSearchCriteriaV2()
                                             {
                                                 ItemBanks = itemBanks,
                                                 CourseList = filteredCourses,
                                                 AddendumType = selectedAddendumTypes,
                                                 AddendumGenre = selectedAddendumGenres,
                                                 UserAccessItemReservations = "",
                                                 Text = searchText,
                                                 TextOpt = searchOption,                                                 
                                                 SortKeyword = sortField,
                                                 courseSelected = selectedCourses.Count > 0 ? true : false,
                                                 ExpirationStatus = selectedExpirationStatus,
                                                 ExpirationDateRange = selectedExpirationDateRange
                                             };

			return asc;
		}
        protected void BtnImpersonateClick(object sender, EventArgs e)
        {
            lblError.Text = "";
            lblError.Visible = false;

            SessObj = (SessionObject)Session["SessionObject"];
            if (SessObj == null || SessObj.LoggedInUser == null)
            {
                Session.Abandon();
                return;
            }
            string message = "";

            if (String.IsNullOrEmpty(UserToImpersonate.Text) || String.IsNullOrEmpty(ImpersonatePW.Text))
            {
                lblError.Text = "Please enter a valid username and password";
                lblError.Visible = true;
            }else{
                var distParms = DistrictParms.LoadDistrictParms();
                string uid = UserToImpersonate.Text;

                
                lblError.Text = "";
                lblError.Visible = false;

                if (SessObj.LoggedInUser.HasPermission(Permission.Access_ImpersonateUserAccess) && distParms.ImpersonateUserAccess && Encryption.EncryptString(ImpersonatePW.Text).Equals(distParms.ImpersonateUserAccessPW))
                {
                    message = "User:"******" is now impersonating user:"******"GlobalInputs"] is no longer referenced in the code. Please use AppSettings.GlobalInputs instead.
                    SessObj.GlobalInputs = gi;
                    Session["GlobalInputs"] = gi;
                    //******* 20121029 DHB Stop code changes. 
                    MembershipUser user = Membership.GetUser(uid);
                    if (user == null)
                    {
                        lblError.Text = "Username " + uid + " not found";
                        lblError.Visible = true;
                        return;
                    }
                    SessObj.LoggedInUser = new ThinkgateUser(user);

                    gi.Add("UserID", SessObj.LoggedInUser.UserId.ToString());
                    gi.Add("UserPage", SessObj.LoggedInUser.Page.ToString());
                    gi.Add("UserName", SessObj.LoggedInUser.UserName);

                    Session["SessionObject"] = SessObj;
                    
                    ThinkgateEventSource.Log.ApplicationEvent(MethodBase.GetCurrentMethod().DeclaringType.ToString() + "->" + MethodBase.GetCurrentMethod().Name, message, "IMPERSONATION");

                    Standpoint.Core.Security.UserImpersonation.ImpersonateUser(uid, "~/PortalSelection.aspx");
                    Response.Redirect("~/PortalSelection.aspx", true);
                }
                else
                {
                    lblError.Text = "Error, you do not have access to impersonate.";
                    lblError.Visible = true;
                    message = "User:"******" just attempted to impersonate user:"******"->" + MethodBase.GetCurrentMethod().Name, message);
                }
            }
        }
        /// <summary>
        /// Builds the QuestionSearchCriteria. Used both from Search Button and from Service
        /// </summary>
        public static ItemImageSearchCriteriaV2 BuildSearchCriteriaObject(ThinkgateUser user, CriteriaController criteriaController, string requestedSortField = null)
        {
            
            /* Sort */
            string sortField = null;
            NameValue nvSortField = SortFields().Find(x => x.Name == requestedSortField);   // ensure that the user given value for sort is in the defined list of options
            if (nvSortField != null) sortField = nvSortField.Value;

            /* Item Banks - Remove from master list based on filter if given */
            var itemBanks = ItemBankMasterList.GetItemBanksForUser(user);
            var selectedItemBanks = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("ItemBank").Select(x => x.Text);
            if (selectedItemBanks.Any()) itemBanks.DeleteByLabel(selectedItemBanks);

            /* Text Search */
            string searchText = string.Empty;
            string searchOption = string.Empty;
            var txtSearchList = criteriaController.ParseCriteria<TextWithDropdown.ValueObject>("TextSearch");
            if (txtSearchList.Count > 0)
            {
                // we ensure that the value the user gave us for text search type is a valid option
                var confirmedOption = TextSearchDropdownValues().Find(x => x.Name == txtSearchList[0].Option) ?? TextSearchDropdownValues().First();
                if (!String.IsNullOrEmpty(txtSearchList[0].Text))
                {
                    searchText = txtSearchList[0].Text;
                    searchOption = confirmedOption.Value;
                }
            }

            /* Courses */
            var selectedGrades = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Grade").Select(x => x.Text).ToList();
            var selectedSubjects = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Subject").Select(x => x.Text).ToList();
            var selectedCourses = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Course").Select(x => x.Text).ToList();
            var selectedStandardSets = new drGeneric_String(criteriaController.ParseCriteria<CheckBoxList.ValueObject>("StandardSet").Select(x => x.Text));     // take straight to drGeneric_String because it's going to SQL
            var filteredCourses = CourseMasterList.GetStandardCoursesForUser(user).FilterByGradesSubjectsStandardSetsAndCourse(selectedGrades, selectedSubjects, selectedStandardSets, selectedCourses);

            var selectedExpirationStatus = criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault() != null ?
            criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault().Value : "I";
            if (!ShowExpiredItems)
            {
                selectedExpirationStatus = "E";

            }
            drGeneric_String_String selectedExpirationDateRange = new drGeneric_String_String();
            foreach (var val in criteriaController.ParseCriteria<DateRange.ValueObject>("ExpirationDateRange"))
            {
                selectedExpirationDateRange.Add(val.Type == "Start" ? "CreatedDateStart" : "CreatedDateEnd", val.Date);
            }




            /* Build Criteria Object */
            var asc = new ItemImageSearchCriteriaV2()
                                             {
                                                 ItemBanks = itemBanks,
                                                 StandardCourses = filteredCourses,
                                                 TextWords = searchText,
                                                 TextWordsOpt = searchOption,
                                                 GradeLimited = selectedGrades.Count > 0,
                                                 SubjectLimited = selectedSubjects.Count > 0,
                                                 CourseLimited = selectedCourses.Count > 0,
                                                 SortBy = sortField == "ItemBank" || sortField == "Standard"
                                                     ? null
                                                     : sortField,
                                                 ExpirationStatus = selectedExpirationStatus,
                                                 ExpirationDateRange = selectedExpirationDateRange
                                             };
            
            return asc;
        }
        protected new void Page_Init(object sender, EventArgs e)
        {
            base.Page_Init(sender, e);
            Master.Search += new SearchMaster.SearchHandler(SearchHandler);
            if (!IsPostBack)
            {
                LoadSearchScripts();


                DistrictParms parms = DistrictParms.LoadDistrictParms();
                ShowExpiredItems = (Request.QueryString["ShowExpiredItems"] != "No" && parms.AllowSearchForCopyRightExpiredContent);
                if (!ShowExpiredItems)
                    ExpirationStatusDateRange.DDLExpirationStatus.Visible = false;

                ImageWebFolder = (Request.ApplicationPath.Equals("/") ? string.Empty : Request.ApplicationPath) + "/Images/";

                if (!UserHasPermission(Permission.Icon_Expand_Item))
                {
                    ExpandPerm_IconWidth = "0px";
                    ExpandPerm_onclick = "";
                }
                else
                {
                    ExpandPerm_IconWidth = "17px";
                    ExpandPerm_onclick = "onclick=\"window.open('" + clientFolder + "/Record/RubricPage.aspx?xID={{:ID_Encrypted}}');\"";
                }

                var serializer = new JavaScriptSerializer();

                var itemBankEditTbl = ItemBankMasterList.GetItemBanksForUser(SessionObject.LoggedInUser, ThinkgatePermission.PermissionLevelValues.ItemBankEdit, "Search");
                var itemBankCopyTbl = ItemBankMasterList.GetItemBanksForUser(SessionObject.LoggedInUser, ThinkgatePermission.PermissionLevelValues.ItemBankCopy, "Search");
                serializer.RegisterConverters(new JavaScriptConverter[] { new ToStringSerializer() });
                string renderIBEditArray = "var IBEditArray = [" + serializer.Serialize(itemBankEditTbl) + "]; ";
                renderIBEditArray += "var IBCopyArray = [" + serializer.Serialize(itemBankCopyTbl) + "]; ";
                ScriptManager.RegisterStartupScript(this, typeof(string), "IBEditArray", renderIBEditArray, true);


#if DEBUG
                clientFolder = "";
#else
                clientFolder = AppSettings.AppVirtualPath == "/" ? "" : AppSettings.AppVirtualPath;
#endif

                if (UserHasPermission(Permission.Icon_Expand_Addendum))
                {
                    ExpandPerm_IconWidth = "17px";
                    ExpandPerm_onclick = "onclick=\"window.open('" + clientFolder + "/Record/AddendumPage.aspx?xID={{:ID_Encrypted}}');\"";
                }
                else
                {
                    ExpandPerm_IconWidth = "0px";
                    ExpandPerm_onclick = "";
                }

                var courses = CourseMasterList.GetStandardCoursesForUser(SessionObject.LoggedInUser);
                ctrlGradeSubjectCourseStandardSet.JsonDataSource = serializer.Serialize(courses.BuildJsonArray());
                ctrlGradeSubjectCourseStandardSet.ChkGrade.DefaultTexts = PossibleDefaultTexts(Request.QueryString["grade"]);
                ctrlGradeSubjectCourseStandardSet.ChkSubject.DefaultTexts = PossibleDefaultTexts(Request.QueryString["subject"]);
                ctrlGradeSubjectCourseStandardSet.CmbCourse.DefaultTexts = PossibleDefaultTexts(Request.QueryString["coursename"]);
                //ctrlRubricType.DataSource = new List<String> {"Holistic", "Advanced"};
                drGeneric_String_String lstRubrics = new drGeneric_String_String();
                lstRubrics.Add("Holistic", "B");
                lstRubrics.Add("Analytical", "A");
                System.Data.DataTable dtRubricTypes = lstRubrics.ToDataTable();
                ctrlRubricType.DataTextField = "Name";
                ctrlRubricType.DataValueField = "Value";
                ctrlRubricType.DataSource = dtRubricTypes;

                dtItemBank dtItemBank = ItemBankMasterList.GetItemBanksForUser(SessionObject.LoggedInUser).DistinctByLabel();

                TestCategory = Request.QueryString["TestCategory"];

                if (TestCategory != null && TestCategory == AssessmentCategories.District.ToString())
                {
                    for (var rowIndex = dtItemBank.Rows.Count - 1; rowIndex >= 0; rowIndex--)
                    {
                        if (dtItemBank.Rows[rowIndex]["Label"].ToString() == "Personal")
                        { dtItemBank.Rows[rowIndex].Delete(); }
                    }
                }

                cblItemBank.DataSource = dtItemBank;
                string rubricType = Request.QueryString["rubrictype"];
                if (!String.IsNullOrEmpty(rubricType))
                {
                    ctrlRubricType.DefaultTexts = new List<string> { rubricType };
                    ctrlRubricType.ReadOnly = true;
                }
                txtSearch.DataSource = TextSearchDropdownValues();
                SortBar.DataSource = SortFields();
            }
        }