public Criterion()
 {
     DataTextField = "ListVal";
     DataValueField = "ID";
     IsHeader = true;
     Object = null;
     Visible = true;
     StandardSelection = new StandardSelections(null, null, null, null, null);
     CurriculumSelection = new CurriculumSelections(null, null, null, null);
     SchoolGradeNameSelection = new SchoolGradeNameSelections(null, null, null, null);
 }
 public Criterion()
 {
     DataTextField = string.Empty;
     DataValueField = string.Empty;
     Key = string.Empty;
     Value = new KeyValuePair(string.Empty, string.Empty);
     Dependencies = new List<KeyValuePair>();
     Header = string.Empty;
     Locked = false;
     // TODO:  MERGE ISSUE
     //UIType = UIType.None;
     HandlerName = string.Empty;
     DefaultValue = null;
     IsUpdatedByUser = false;
     Visible = true;
     AutoHide = true;
     ToValue = new KeyValuePair(string.Empty, string.Empty);
     StandardSelection = new StandardSelections(null, null, null, null, null);
     CurriculumSelection = new CurriculumSelections(null, null, null, null);
     SchoolGradeNameSelection = new SchoolGradeNameSelections(null, null, null, null);
 }
		/// <summary>
		///  SearchResourcesWithCriteria
		/// </summary>
		/// <returns>List</returns>
		public List<Resource> SearchResourcesWithCriteria(bool search = false)
		{
			Criteria criteria = SearchControl.GetCriteria();

			ResourceTypes resUnitType;
			TagCriteriaSelectionParameters tagCriteriaSelectionParameters = new TagCriteriaSelectionParameters();
			string sourceSelection = "";
			string selectedTypes = "";
			string selectedSubTypes = "";
			string textSearch = "";
            List<int> averageRating = new List<int>();
		    DateTime? startExpirationDate = default(DateTime?);
            DateTime? endExpirationDate = default(DateTime?);
			StandardSelections selectedStandards = new StandardSelections();
			StandardSelections selectedAssessed = new StandardSelections();
			StandardSelections selectedTeaches = new StandardSelections();
			StandardSelections selectedRequires = new StandardSelections();
			CurriculumSelections selectedCurriculums = new CurriculumSelections();

            SchoolGradeNameSelections selectedSchoolGradeName = new SchoolGradeNameSelections();

			string selectedMediaType = "";
			string selectedLanguageType = "";

			foreach (Criterion cr in criteria.Criterias)
			{
				switch (cr.Key)
				{
					case "Source":
						sourceSelection = cr.Value.Key;
						break;
					case "Type":
						selectedTypes = cr.Value.Key;
						break;
					case "SubType":
						selectedSubTypes = cr.Value.Key;
						break;
					case "Text":
						textSearch = cr.Value.Value;
						break;
					case "Keywords":
						tagCriteriaSelectionParameters.Keywords = cr.Value.Value;
						break;
					case "Standards":
						selectedStandards.StandardSet = cr.StandardSelection.StandardSet;
						selectedStandards.Grade = cr.StandardSelection.Grade;
						selectedStandards.Subject = cr.StandardSelection.Subject;
						selectedStandards.Course = cr.StandardSelection.Course;
						selectedStandards.Key = cr.Value.Key;
						break;
					case "Curriculum":
						selectedCurriculums.Grade = cr.CurriculumSelection.Grade;
						selectedCurriculums.Subject = cr.CurriculumSelection.Subject;
						selectedCurriculums.Course = cr.CurriculumSelection.Course;
						selectedCurriculums.Key = cr.Value.Key;
						break;
                    case "ExpirationDate":
                        if (cr.Value.Value.IsNotNullOrWhiteSpace())
                        {
                            string[] dateRangeString = cr.Value.Value.Split(':');
                            startExpirationDate = dateRangeString[0].IsNullOrWhiteSpace() ? default(DateTime?) : Convert.ToDateTime(dateRangeString[0]);
                            endExpirationDate = dateRangeString[1].IsNullOrWhiteSpace() ? default(DateTime?) : Convert.ToDateTime(dateRangeString[1]);

                        }
                        break;
                    case "AverageRating":
                        if (cr.Value.Value.IsNotNullOrWhiteSpace())
                        {
                            averageRating = new List<int>(cr.Value.Value.Replace(", ", ",").Split(',').Select(int.Parse));
                        }
                        break;
					case "MediaType":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
						{
							tagCriteriaSelectionParameters.MediaType =
								new List<int>(cr.Value.Value.Replace(" ", "").Split(',').Select(int.Parse));
                            selectedMediaType =
                                tagCriteriaSelectionParameters.MediaType[0].ToString(CultureInfo.InvariantCulture);
						}
						break;
					case "Language":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
						{
							selectedLanguageType = cr.Value.Value;
                            tagCriteriaSelectionParameters.Language =
                                (int)Enum.Parse(typeof(LanguageType), cr.Value.Value);
						}
						break;
					case "Grades":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
                            tagCriteriaSelectionParameters.GradeLevel =
                                new List<string>(cr.Value.Value.Replace(", ", ",").Split(','));
						break;
					case "Assessed":
						selectedAssessed.StandardSet = cr.StandardSelection.StandardSet;
						selectedAssessed.Grade = cr.StandardSelection.Grade;
						selectedAssessed.Subject = cr.StandardSelection.Subject;
						selectedAssessed.Course = cr.StandardSelection.Course;
						selectedAssessed.Key = cr.Value.Key;
						if (IEnumerableExtensions.IsNotNullOrEmpty(GetListOfStandards(selectedAssessed)))
							tagCriteriaSelectionParameters.AssessedStandardIds =
								new List<int>(GetListOfStandards(selectedAssessed).Split(',').Select(int.Parse));
						break;
					case "Teaches":
						selectedTeaches.StandardSet = cr.StandardSelection.StandardSet;
						selectedTeaches.Grade = cr.StandardSelection.Grade;
						selectedTeaches.Subject = cr.StandardSelection.Subject;
						selectedTeaches.Course = cr.StandardSelection.Course;
						selectedTeaches.Key = cr.Value.Key;
						if (IEnumerableExtensions.IsNotNullOrEmpty(GetListOfStandards(selectedTeaches)))
							tagCriteriaSelectionParameters.TeachesStandardIds =
								new List<int>(GetListOfStandards(selectedTeaches).Split(',').Select(int.Parse));
						;
						break;
					case "Requires":
						selectedRequires.StandardSet = cr.StandardSelection.StandardSet;
						selectedRequires.Grade = cr.StandardSelection.Grade;
						selectedRequires.Subject = cr.StandardSelection.Subject;
						selectedRequires.Course = cr.StandardSelection.Course;
						selectedRequires.Key = cr.Value.Key;
						if (IEnumerableExtensions.IsNotNullOrEmpty(GetListOfStandards(selectedRequires)))
							tagCriteriaSelectionParameters.RequiresStandardIds =
								new List<int>(GetListOfStandards(selectedRequires).Split(',').Select(int.Parse));
						;
						break;
					case "TextComplexity":
						tagCriteriaSelectionParameters.TextComplexity = cr.Value.Value;
						break;
					case "ReadingLevel":
						tagCriteriaSelectionParameters.ReadingLevel = cr.Value.Value;
						break;
					case "EducationalSubject":
						if (cr.Value.Key.IsNotNullOrWhiteSpace())
                            tagCriteriaSelectionParameters.EducationalSubject =
                                new List<string>(cr.Value.Value.Replace(", ", ",").Split(','));
						break;

					case "InteractivityType":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
							tagCriteriaSelectionParameters.InteractivityType =
								new List<int>(cr.Value.Value.Replace(" ", "").Split(',').Select(int.Parse));

						if (sourceSelection == NationalLearningRegistry)
						{
							tagCriteriaSelectionParameters.InteractivityTypes = new List<string>();
                            DataTable dtActivity =
                                Base.Classes.Assessment.LoadLrmiTagsByLookupEnum((int)Enums.LrmiTags.Activity,
                                    Enums.SelectionType.Assessment.ToString());
						
							List<KeyValuePair<string, string>> theList = new List<KeyValuePair<string, string>>();
							foreach (DataRow row in dtActivity.Rows)
							{
                                theList.Add(new KeyValuePair<string, string>(row["ID"].ToString(),
                                    row["Description"].ToString()));
							}

							foreach (int item in tagCriteriaSelectionParameters.InteractivityType)
							{
                                tagCriteriaSelectionParameters.InteractivityTypes.Add(
                                    theList.First(kvp => kvp.Key == item.ToString()).Value);
							}
						}
						break;

					case "LearningResource":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
							tagCriteriaSelectionParameters.LearningResourceType =
								new List<int>(cr.Value.Value.Replace(" ", "").Split(',').Select(int.Parse));
						break;
					case "EducationalUse":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
							tagCriteriaSelectionParameters.EducationalUse =
								new List<int>(cr.Value.Value.Replace(" ", "").Split(',').Select(int.Parse));

						if (sourceSelection == NationalLearningRegistry)
						{
							tagCriteriaSelectionParameters.EducationalUses = new List<string>();
                            DataTable dtEducationalSubjects =
                                Base.Classes.Assessment.LoadLrmiTagsByLookupEnum((int)Enums.LrmiTags.EducationalUse,
                                    Enums.SelectionType.Resource.ToString());

							List<KeyValuePair<string, string>> theList = new List<KeyValuePair<string, string>>();
							foreach (DataRow row in dtEducationalSubjects.Rows)
							{
                                theList.Add(new KeyValuePair<string, string>(row["ID"].ToString(),
                                    row["Description"].ToString()));
							}

							foreach (int item in tagCriteriaSelectionParameters.EducationalUse)
							{
                                tagCriteriaSelectionParameters.EducationalUses.Add(
                                    theList.First(kvp => kvp.Key == item.ToString()).Value);
							}
						}
						break;
					case "EndUser":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
							tagCriteriaSelectionParameters.EndUser =
								new List<int>(cr.Value.Value.Replace(" ", "").Split(',').Select(int.Parse));

						if (sourceSelection == NationalLearningRegistry)
						{
							tagCriteriaSelectionParameters.EndUsers = new List<string>();
                            DataTable dtEndUsers =
                                Base.Classes.Assessment.LoadLrmiTagsByLookupEnum((int)Enums.LrmiTags.EndUser,
                                    Enums.SelectionType.Resource.ToString());

							List<KeyValuePair<string, string>> theList = new List<KeyValuePair<string, string>>();
							foreach (DataRow row in dtEndUsers.Rows)
							{
                                theList.Add(new KeyValuePair<string, string>(row["ID"].ToString(),
                                    row["Description"].ToString()));
							}

							foreach (int item in tagCriteriaSelectionParameters.EndUser)
							{
                                tagCriteriaSelectionParameters.EndUsers.Add(
                                    theList.First(kvp => kvp.Key == item.ToString()).Value);
							}
						}

						break;
					case "Duration":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
						{
							string[] durationStrings = cr.Value.Value.Split(':');
							tagCriteriaSelectionParameters.TimeRequiredDays = Convert.ToInt32(durationStrings[0]);
							tagCriteriaSelectionParameters.TimeRequiredHours = Convert.ToInt32(durationStrings[1]);
							tagCriteriaSelectionParameters.TimeRequiredMinutes = Convert.ToInt32(durationStrings[2]);
						}
						break;
					case "AgeAppropriate":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
						{
							if (sourceSelection == NationalLearningRegistry)
							{
								string validAges = mapAgeAppropriateToAges(cr.Value.Value);
								if (!string.IsNullOrEmpty(validAges))
								{
									tagCriteriaSelectionParameters.Ages = validAges;
								}
								//cant convert a string like "16-18" to an int
								// this needs to be looked at...
								//tagCriteriaSelectionParameters.AgeAppropriate = Convert.ToInt32(cr.Value.Value);
							}
						}
						break;
					case "Creator":
						tagCriteriaSelectionParameters.Creator = cr.Value.Value;
						break;
					case "Publisher":
						tagCriteriaSelectionParameters.Publisher = cr.Value.Value;
						break;
					case "UsageRights":
						if (cr.Value.Value.IsNotNullOrWhiteSpace())
						{
							tagCriteriaSelectionParameters.UseRightUrl = Convert.ToInt32(cr.Value.Key);

							if (sourceSelection == NationalLearningRegistry)
							{
                                string theURLResult =
                                    GetCreativeCommonsUrls().First(kvp => kvp.Key == cr.Value.Key).Value;

								if (cr.Value.Value.Equals("Custom", StringComparison.OrdinalIgnoreCase))
								{
									theURLResult = cr.Value.Value;
								}

								if (!string.IsNullOrEmpty(theURLResult))
								{
									//TODO: match theURLResult to LRMI tag dropdown items
									tagCriteriaSelectionParameters.UseRightUrlTxt = theURLResult;
									//If no match then set to "CUSTOM" I guess
								}
							}
						}
						break;
                    case "SchoolGradeName":
                        selectedSchoolGradeName.School = cr.SchoolGradeNameSelection.School;
                        selectedSchoolGradeName.Grade = cr.SchoolGradeNameSelection.Grade;
                        selectedSchoolGradeName.Name = cr.SchoolGradeNameSelection.Name; // userid
                        selectedSchoolGradeName.Key = cr.SchoolGradeNameSelection.Key;
                        break;


				}
			}

			string whereclause = "";
			string whereClauseIp = "";
			string whereClauseUp = "";
			string whereClauseLp = "";
			string whereClauseMu = "";
			string whereTextSearch = "";

			List<Resource> resultResource = new List<Resource>();

			if (sourceSelection == "" ||
				sourceSelection == District ||
				sourceSelection == State ||
				sourceSelection == MyDocuments ||
                sourceSelection == InternalSource ||
                sourceSelection == TeacherMyDocs ||
                sourceSelection == SharedDocument)//US15667
			{

				resUnitType = ResourceTypes.All;

				switch (sourceSelection)
				{
					case District:
						resUnitType = ResourceTypes.DistrictDocuments;
						break;
					case State:
						resUnitType = ResourceTypes.StateDocuments;
						break;
					case MyDocuments:
						resUnitType = ResourceTypes.MyDocuments;
						break;
                    case TeacherMyDocs: 
                        resUnitType = ResourceTypes.MyDocuments;
                        break;
                    case SharedDocument:
                        resUnitType = ResourceTypes.SharedDocuments;
                        break;
				}

				if (selectedTypes != null && (selectedTypes.Any() && selectedTypes != ""))
				{
					whereClauseIp = " Type = " + selectedTypes;
					whereClauseLp = " Type = " + selectedTypes;
					whereClauseMu = " Type = " + selectedTypes;
					if (selectedTypes == ((int)LookupDetail.CurriculumUnitMA).ToString(CultureInfo.InvariantCulture))
					{
						whereClauseUp = " Type = " + ((int)LookupDetail.UnitPlan) + " OR Type = " +
										((int)LookupDetail.CurriculumUnitMA);
						resUnitType = ResourceTypes.StateDocuments;
					}
					else
					{
						whereClauseUp = " Type = " + selectedTypes;
					}
					whereclause += whereclause == ""
						? " TYPE in ( " + string.Join(",", selectedTypes.Split(',')) +
						  ") "
						: "AND" + " TYPE in ( " +
						  string.Join(",", selectedTypes.Split(',')) + ") ";
				}
				if (selectedSubTypes.Any() && selectedSubTypes != "")
				{
					whereClauseIp += whereClauseIp == ""
						? " SubType = " + selectedSubTypes
						: " AND" + " SubType = " + selectedSubTypes;
					whereClauseLp += whereClauseLp == ""
						? " SubType = " + selectedSubTypes
						: " AND" + " SubType = " + selectedSubTypes;
					whereClauseMu += whereClauseMu == ""
						? " SubType = " + selectedSubTypes
						: " AND" + " SubType = " + selectedSubTypes;

					if (selectedSubTypes ==
						((int)LookupDetail.StateModelCurriculumUnitForm).ToString(CultureInfo.InvariantCulture))
					{
						whereClauseUp += whereClauseUp == ""
							? " SubType = " + ((int)LookupDetail.UnitPlanForm) + " OR SubType= " +
							  ((int)LookupDetail.StateModelCurriculumUnitForm)
							: " AND" + " SubType = " + ((int)LookupDetail.UnitPlanForm) + " OR SubType= " +
							  ((int)LookupDetail.StateModelCurriculumUnitForm);
						resUnitType = ResourceTypes.StateDocuments;
					}
					else
					{
						whereClauseUp += whereClauseUp == ""
							? " SubType = " + selectedSubTypes
							: " AND" + " SubType = " + selectedSubTypes;
					}
					whereclause += whereclause == ""
						? " SUBTYPE in ( " +
						  string.Join(",", selectedSubTypes.Split(',')) + ")"
						: "AND" + " SUBTYPE in ( " +
						  string.Join(",", selectedSubTypes.Split(',')) + ")";
				}
				if (textSearch.Any() && textSearch.Trim() != "")
				{
					whereclause += whereclause == ""
						? " Name like ( '%" + textSearch.Trim() + "%')"
						: " AND" + " Name like ( '%" + textSearch.Trim() + "%')";
					whereTextSearch = " like ( '%" + textSearch.Trim() + "%')";
				}

				DistrictParms districtParms = DistrictParms.LoadDistrictParms();
				string envState = KenticoHelper.GetKenticoMainFolderName(districtParms.ClientID);
				_districts = new System.Text.StringBuilder();
				_stateDocuments = new System.Text.StringBuilder();
                //US15667
                _sharedDocuments = new System.Text.StringBuilder();
				_districts.Append("/" + envState + "/Districts/");
				_stateDocuments.Append("/" + envState + "/Documents/");
                //US15667
                _sharedDocuments.Append("/" + envState + "/Shared/");

                UserInfo ui = new UserInfo();
                if (!string.IsNullOrEmpty(selectedSchoolGradeName.Name))
                {
                    if ((bool)Session["KenticoEnabled"])
                    {
                        KenticoHelper.KenticoUserName = KenticoHelper.GetKenticoUser(selectedSchoolGradeName.Name);
                        ui = CMS.SiteProvider.UserInfoProvider.GetFullUserInfo(KenticoHelper.KenticoUserName);
                }
                    else
                    { ui = (UserInfo)Session["KenticoUserInfo"]; }
                }
                else
                { ui = (UserInfo)Session["KenticoUserInfo"]; }


				string where = whereclause;
				const string orderBy = "Name";

				TreeProvider treeProvider =
					KenticoHelper.GetUserTreeProvider(_sessionObject.LoggedInUser.ToString());
				DataSet resourceDs = KenticoHelper.ExpandedSearchDocumentType(ui, ResourceClassName,
					treeProvider, resUnitType, where, orderBy, filterUsageRightExpiredContent);

				List<Resource> lstResource = new List<Resource>();
                List<Resource> listResourceTemp = new List<Resource>();

				DataSet lookupDataSet = new DataSet();
				DataClassInfo customTable = DataClassInfoProvider.GetDataClass("TG.LookupDetails");
				if (customTable != null)
				{
					lookupDataSet = (new CustomTableItemProvider(ui)).GetItems("TG.LookupDetails",
						string.Empty, string.Empty);
				}

				//For IP, UP, LP, and MU
				List<Resource> lstIpup = GetPlans(ui, treeProvider, whereClauseIp, whereClauseUp, whereClauseLp,
					whereClauseMu, whereTextSearch, lookupDataSet, districtParms, resUnitType);



				if (!string.IsNullOrWhiteSpace(selectedStandards.StandardSet) ||
					!string.IsNullOrWhiteSpace(selectedCurriculums.Grade))
				{
					if (!string.IsNullOrWhiteSpace(selectedStandards.StandardSet))
					{

						string stringListOfStandards = GetListOfStandards(selectedStandards);
						List<CmsCustomTable> lstStandards = GetDocToStandardsFromCms(ui,
							stringListOfStandards);

						if (lstStandards != null && lstStandards.Count > 0)
						{
							if (resourceDs != null && resourceDs.Tables[0].Rows.Count > 0)
							{
					            listResourceTemp = (from res in resourceDs.Tables[0].AsEnumerable()
											   join ctdtl in lookupDataSet.Tables[0].AsEnumerable() on
												   Convert.ToInt32(res["type"].ToString()) equals
												   Convert.ToInt32(ctdtl["enum"].ToString())
											   join stdtl in lookupDataSet.Tables[0].AsEnumerable() on
												   Convert.ToInt32(res["subtype"].ToString()) equals
												   Convert.ToInt32(stdtl["enum"].ToString())
					                                join s in lstStandards on
					                                    Convert.ToInt32(res["DocumentNodeID"]) equals s.DocId
											   select
												   new Resource
												   {
													   Source =
                                                res["NodeAliasPath"].ToString()
					                                                                .IndexOf(
					                                                                    _districts.ToString(),
					                                                                    StringComparison.Ordinal)
					                                            >= 0
															   ? District
                                                    : res["NodeAliasPath"].ToString()
					                                                                      .IndexOf(
					                                                                          _stateDocuments
					                                            .ToString(),
					                                                                          StringComparison
					                                            .Ordinal) >=
                                                      0
																   ? State
                                                    : res["NodeAliasPath"].ToString()
                                                        .IndexOf(_sharedDocuments.ToString(), StringComparison.Ordinal) >=
                                                      0
                                                                   ? SharedDocument //US15667
																   : MyDocuments,
													   ID = Convert.ToInt32(res["DocumentID"]),
													   DocumentNodeID = Convert.ToInt32(res["DocumentNodeID"]),
													   DocumentForeignKeyValue =
					                                            Convert.ToInt32(
					                                                res["DocumentForeignKeyValue"].ToString()),
													   DocumentType = res["ClassName"].ToString(),
													   ID_Encrypted = "",
													   NodeAliasPath = res["NodeAliasPath"].ToString(),
													   ResourceName = res["Name"].ToString(),
													   Description = res["Description"].ToString(),
													   Type = ctdtl["Description"].ToString(),
													   Subtype = stdtl["Description"].ToString(),
													   ViewLink =
					                                            string.IsNullOrEmpty(
					                                                res["AttachmentName"].ToString())
															   ? ""
															   : res["AttachmentName"].ToString(),
					                                        ExpirationDate =
					                                            res["ExpirationDate"] == DBNull.Value
					                                                ? default(DateTime)
					                                                : Convert.ToDateTime(res["ExpirationDate"]),
					                                        AverageRating =
					                                            res["AverageRating"] == DBNull.Value
					                                                ? default(decimal)
                                                                    : Convert.ToDecimal(res["AverageRating"]),
                                                                    DocumentCreatedWhen= res["DocumentModifiedWhen"] == DBNull.Value
                                                            ? default(DateTime)
                                                            : Convert.ToDateTime(res["DocumentModifiedWhen"])
												   }).Distinct().ToList<Resource>();
							}

						lstIpup = (from res in lstIpup
										   join s in lstStandards on res.DocumentNodeID equals s.DocId
										   select res).ToList<Resource>();
							
					        if (lstResource.Count > 0 || isFilteredResourceEmpty)
					            lstResource = (from res in lstResource
					                           join t in listResourceTemp on res.ID equals t.ID
					                           select res).ToList<Resource>();
					        else
					            lstResource.AddRange(listResourceTemp);

					        if (listResourceTemp.Count == 0)
					            isFilteredResourceEmpty = true;
						}
                        else
					    {
                            lstIpup = new List<Resource>();
					        lstResource = new List<Resource>();
					    }

					}

					if (!string.IsNullOrWhiteSpace(selectedCurriculums.Grade))
					{

						List<CmsCustomTable> lstCurriculum = GetDocToCurucullumsFromCms(ui);
						List<object> listCurriculums = GetCurriculumsIDsFromSelectedCriteria(selectedCurriculums);
						lstCurriculum = lstCurriculum.FindAll(f => listCurriculums.Contains(f.Id));
                        if (lstCurriculum.Count > 0)
                        {
						if (resourceDs != null && resourceDs.Tables[0].Rows.Count > 0)
						{
					            listResourceTemp = (from res in resourceDs.Tables[0].AsEnumerable()
										   join ctdtl in lookupDataSet.Tables[0].AsEnumerable() on
											   Convert.ToInt32(res["type"].ToString()) equals
											   Convert.ToInt32(ctdtl["enum"].ToString())
										   join stdtl in lookupDataSet.Tables[0].AsEnumerable() on
											   Convert.ToInt32(res["subtype"].ToString()) equals
											   Convert.ToInt32(stdtl["enum"].ToString())
					                                join s in lstCurriculum on
					                                    Convert.ToInt32(res["DocumentNodeID"]) equals s.DocId
										   select
											   new Resource
											   {
												   Source =
                                            res["NodeAliasPath"].ToString()
					                                                                .IndexOf(
					                                                                    _districts.ToString(),
					                                                                    StringComparison.Ordinal)
					                                            >= 0
														   ? District
                                                : res["NodeAliasPath"].ToString()
					                                                                      .IndexOf(
					                                                                          _stateDocuments
					                                            .ToString(),
					                                                                          StringComparison
					                                            .Ordinal) >= 0
															   ? State
                                                : res["NodeAliasPath"].ToString()
                                                    .IndexOf(_sharedDocuments.ToString(), StringComparison.Ordinal) >= 0
                                                               ? SharedDocument//US15667
															   : MyDocuments,
												   ID = Convert.ToInt32(res["DocumentID"]),
												   DocumentNodeID = Convert.ToInt32(res["DocumentNodeID"]),
												   DocumentForeignKeyValue =
					                                            Convert.ToInt32(
					                                                res["DocumentForeignKeyValue"].ToString()),
												   DocumentType = res["ClassName"].ToString(),
												   ID_Encrypted = "",
												   NodeAliasPath = res["NodeAliasPath"].ToString(),
												   ResourceName = res["Name"].ToString(),
												   Description = res["Description"].ToString(),
												   Type = ctdtl["Description"].ToString(),
												   Subtype = stdtl["Description"].ToString(),
												   ViewLink =
					                                            string.IsNullOrEmpty(
					                                                res["AttachmentName"].ToString())
														   ? ""
														   : res["AttachmentName"].ToString(),
					                                        ExpirationDate =
					                                            res["ExpirationDate"] == DBNull.Value
					                                                ? default(DateTime)
					                                                : Convert.ToDateTime(res["ExpirationDate"]),
					                                        AverageRating =
					                                            res["AverageRating"] == DBNull.Value
					                                                ? default(decimal)
                                                                    : Convert.ToDecimal(res["AverageRating"]),
                                                            DocumentCreatedWhen= res["DocumentModifiedWhen"] == DBNull.Value
                                                                   ? default(DateTime)
                                                                   : Convert.ToDateTime(res["DocumentModifiedWhen"])
												  
											   }).ToList<Resource>();
						}

						
							lstIpup = (from res in lstIpup
									   join s in lstCurriculum on res.DocumentNodeID equals s.DocId
									   select res).ToList<Resource>();

					        if (lstResource.Count > 0  || isFilteredResourceEmpty)
					            lstResource = (from res in lstResource
					                           join t in listResourceTemp on res.ID equals t.ID
					                           select res).ToList<Resource>();
					        else
					            lstResource.AddRange(listResourceTemp);

					        if (listResourceTemp.Count == 0)
					            isFilteredResourceEmpty = true;
						}
                        else
					    {
                            lstIpup = new List<Resource>();
					        lstResource = new List<Resource>();
					    }
					}

				}
				else
				{

					if (resourceDs != null && resourceDs.Tables[0].Rows.Count > 0)
					{

						listResourceTemp = (from res in resourceDs.Tables[0].AsEnumerable()
									   join ctdtl in lookupDataSet.Tables[0].AsEnumerable() on
										   Convert.ToInt32(res["type"].ToString()) equals Convert.ToInt32(ctdtl["enum"].ToString())
									   join stdtl in lookupDataSet.Tables[0].AsEnumerable() on
										   Convert.ToInt32(res["subtype"].ToString()) equals
										   Convert.ToInt32(stdtl["enum"].ToString())
									   select
										   new Resource
										   {
											   Source =
                                        res["NodeAliasPath"].ToString()
                                            .IndexOf(_districts.ToString(), StringComparison.Ordinal) >= 0
													   ? District
                                            : res["NodeAliasPath"].ToString()
                                                .IndexOf(_stateDocuments.ToString(), StringComparison.Ordinal) >= 0
														   ? State
                                            : res["NodeAliasPath"].ToString()
                                                .IndexOf(_sharedDocuments.ToString(), StringComparison.Ordinal) >= 0
                                                           ? SharedDocument //US15667
														   : MyDocuments,
											   ID = Convert.ToInt32(res["DocumentID"]),
											   DocumentForeignKeyValue = Convert.ToInt32(res["DocumentForeignKeyValue"].ToString()),
											   DocumentType = res["ClassName"].ToString(),
											   ID_Encrypted = "",
											   NodeAliasPath = res["NodeAliasPath"].ToString(),
											   ResourceName = res["Name"].ToString(),
											   Description = res["Description"].ToString(),
											   Type = ctdtl["Description"].ToString(),
											   Subtype = stdtl["Description"].ToString(),
											   ViewLink =
												   string.IsNullOrEmpty(res["AttachmentName"].ToString())
													   ? ""
													   : res["AttachmentName"].ToString(),
											   DocumentNodeID = Convert.ToInt32(res["DocumentNodeID"]),
                                               ExpirationDate = res["ExpirationDate"] == DBNull.Value ? default(DateTime) : Convert.ToDateTime(res["ExpirationDate"]),
                                                    AverageRating = res["AverageRating"] == DBNull.Value ? default(decimal) : Convert.ToDecimal(res["AverageRating"]),
                                                    DocumentCreatedWhen= res["DocumentModifiedWhen"] == DBNull.Value? default(DateTime): Convert.ToDateTime(res["DocumentModifiedWhen"])												  
										   }).ToList<Resource>();
					}

                    if (lstResource.Count > 0  || isFilteredResourceEmpty )
                        lstResource = (from res in lstResource
                                       join t in listResourceTemp on res.ID equals t.ID
                                       select res).ToList<Resource>();
                    else
                        lstResource.AddRange(listResourceTemp);

                    

				}

				if (lstIpup.Count > 0)
				{
					lstResource.AddRange(lstIpup);
				}

				string hostURL = Request.Url.ToString();
				try
				{
					int hostPosition = hostURL.LastIndexOf(districtParms.ClientID) - 1;
					hostURL = hostURL.Substring(0, hostPosition);
				}
				catch
				{
					hostURL = "";
				}

			   if (startExpirationDate != default(DateTime?))
                {
                    lstResource = lstResource.FindAll(unl => unl.ExpirationDate >= startExpirationDate && unl.ExpirationDate != default(DateTime));
                }

                if (endExpirationDate != default(DateTime?))
                {
                    lstResource = lstResource.FindAll(unl => unl.ExpirationDate <= endExpirationDate && unl.ExpirationDate != default(DateTime));
                }

			    if (averageRating.Count > 0)
			    {
			        List<RatingRange> ratingRange = _reviewFacade.GetRatingFilterForItemSearch().ToList();
                    List<Resource> newLstResource = new List<Resource>();
			        decimal maxvalue;
			        decimal minvalue;
			        foreach (var id in averageRating )
			        {
			            maxvalue = ratingRange.Find(x => x.Id == id).EndValue;
                        minvalue = ratingRange.Find(x => x.Id == id).StartValue;
			            newLstResource.AddRange(
			                lstResource.FindAll(
			                    unl => unl.AverageRating >= minvalue && unl.AverageRating <= maxvalue).ToList());

			        }
			        lstResource = newLstResource;
			    }

			    resultResource =
					lstResource.GroupBy(
						x =>
							new
							{
								x.Source,
								x.ID,
								x.DocumentNodeID,
								x.ResourceName,
                                x.ResourceNameReadOnly,
								x.Description,
								x.Type,
								x.Subtype,
								x.ViewLink,
								x.NodeAliasPath,
								x.DocumentForeignKeyValue,
								x.DocumentType,
                                x.ExpirationDate,
                                x.AverageRating,
                                x.DocumentCreatedWhen
							})
						.Select(r => new Resource
						{
							Source = r.Key.Source,
							ID = r.Key.ID,
							DocumentNodeID = r.Key.DocumentNodeID,
							ResourceName = r.Key.ResourceName,
                            ResourceNameReadOnly = r.Key.ResourceName,
							Description = r.Key.Description,
							Type = r.Key.Type,
							Subtype = r.Key.Subtype,
							//ViewLink = string.IsNullOrWhiteSpace(r.Key.ViewLink) ? "" : hostURL + KenticoHelper.KenticoVirtualFolderRelative + "/cmspages/getfile.aspx?guid=" + r.Key.ViewLink + "&disposition=inline",
							ViewLink =
								string.IsNullOrWhiteSpace(r.Key.ViewLink)
									? ""
                                    : KenticoHelper.KenticoVirtualFolderRelative + "/cmspages/getfile.aspx?guid=" +
                                      r.Key.ViewLink +
									  "&disposition=inline",
							NodeAliasPath = r.Key.NodeAliasPath,
							DocumentForeignKeyValue = r.Key.DocumentForeignKeyValue,
							DocumentType = r.Key.DocumentType,
                            ExpirationDate = r.Key.ExpirationDate,
                            AverageRating = r.Key.AverageRating,
                            DocumentCreatedWhen=r.Key.DocumentCreatedWhen
						}).ToList();

                resultResource = resultResource.OrderByDescending(rslRsc => rslRsc.DocumentCreatedWhen).ToList();

				if (tagCriteriaSelectionParameters != null)
				{
					if (!TagCriteriaSelectionParameters.IsEmpty(tagCriteriaSelectionParameters))
					{
						List<Resource> filteredByTags = FilterResourcesByTags(resultResource,
							tagCriteriaSelectionParameters);
						resultResource = filteredByTags;
					}
				}
			}
			else
			{
				string resourceTextSearch = textSearch.Trim() == ""
					? LearningMediaFacets.SearchTermAll
					: textSearch.Trim();

				if (sourceSelection == NationalLearningRegistry)
				{
                    NLRSearchParameters nlrSearchParameters = getNLRSearchParameters(resourceTextSearch,
                        tagCriteriaSelectionParameters);
					resultResource = GetLearningRegistryResources(search, nlrSearchParameters);
				}

				if (sourceSelection == PBSLearningMedia)
				{
					if (tagCriteriaSelectionParameters.GradeLevel == null)
						tagCriteriaSelectionParameters.GradeLevel = new List<string>();
                    resultResource = GetWgbhResources(search, tagCriteriaSelectionParameters.GradeLevel,
                        resourceTextSearch,
						selectedMediaType, selectedLanguageType);
				}
			}
			return resultResource;
		}