using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Orciid.Core;
using System.Xml;
using Orciid.UserControls;

namespace Orciid
{
	public class SearchWebForm : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Button SearchButton;
		protected System.Web.UI.WebControls.CheckBoxList CollectionCheckBoxList;
		protected Orciid.UserControls.CollectionSelection CollectionSelection;
		protected System.Web.UI.WebControls.TextBox KeywordField;
		protected System.Web.UI.WebControls.Repeater FieldRepeater;
		protected System.Web.UI.WebControls.Panel SearchCriteriaPanel;
		protected System.Web.UI.WebControls.Button ClearFormButton;

		private int numSelectedCollections = 0;
		protected System.Web.UI.HtmlControls.HtmlGenericControl LoadSavedSearchDiv;
		protected System.Web.UI.HtmlControls.HtmlTableRow ImagesAddedSelection;
		protected System.Web.UI.HtmlControls.HtmlTableRow ImagesUpdatedSelection;
		protected System.Web.UI.WebControls.DropDownList SavedSearchDropDownList;
		protected System.Web.UI.WebControls.Button LoadSavedSearchButton;
		protected System.Web.UI.WebControls.Button RemoveSavedSearchButton;
		protected System.Web.UI.WebControls.DropDownList ImagesAddedDropDownList;
		protected System.Web.UI.WebControls.DropDownList ImagesUpdatedDropDownList;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CollectionsLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl KeywordLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImagesAddedLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImagesAddedWithinLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImagesAddedDaysLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImagesUpdatedLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImagesUpdatedWithinLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImagesUpdatedDaysLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl SavedSearchesLabelSpan;
		protected System.Web.UI.WebControls.Button RunSavedSearchButton;
		protected System.Web.UI.WebControls.Button RecentlyAddedSavedSearchButton;
		private Search.SearchParameters searchdefaults = null;

		private Hashtable displaylabels;

		private CollectionSelectionEntry[] GetCollectionEntries()
		{
			ArrayList list = new ArrayList();
			foreach (Collection c in Collection.GetCollections())
			{
				CollectionSelectionEntry entry = new CollectionSelectionEntry();
				entry.CollectionID = c.ID;
				if (searchdefaults != null)
					foreach (Collection coll in searchdefaults.collections)
						if (coll.ID == entry.CollectionID)
						{
							entry.Selected = true;
							break;
						}
				list.Add(entry);
			}
			return (CollectionSelectionEntry[])list.ToArray(typeof(CollectionSelectionEntry));
		}

		protected string GetFieldLabel(Field field)
		{
			if (numSelectedCollections > 1 && field.DCName != null)
			{
				string dcname = field.DCName.ToLower();
				if (displaylabels.ContainsKey(dcname))
				{
					string l = (string)displaylabels[dcname];
					return (l.Length > 40 ? l.Substring(0, 37) + "..." : l);
				}
				else
					return field.DCName;
			}
			else
				return field.Label;
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				if (Session["LastSearch"] != null)
					searchdefaults = new Search.SearchParameters((string)Session["LastSearch"]);
				CollectionSelection.DataSource = GetCollectionEntries();
				CollectionSelection.DataBind();
			}

			int[] s = CollectionSelection.GetSelection();
			numSelectedCollections = (s == null ? 0 : s.Length);

			if (!IsPostBack)
			{
				DataBindSavedSearches();
			}

			PrepareFields();
			DisableButtonOnClick(SearchButton, GetLocalString(this, "SearchingButtonLabel", "Searching..."));			
		}

		private void DataBindSavedSearches()
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			SavedSearch[] searches = SavedSearch.GetAll(user);
			if (searches != null && searches.Length > 0)
			{
				LoadSavedSearchDiv.Visible = true;
				SavedSearchDropDownList.Items.Clear();
				foreach (SavedSearch search in searches)
				{
					string title;
					if (search.NewRecords > 0)
						title = String.Format(
							GetLocalString(this, "SavedSearchesRecordsAdded", "{0} ({1} added recently)"), 
							search.Title, search.NewRecords);
					else
						title = search.Title;
					SavedSearchDropDownList.Items.Add(new ListItem(title, search.ID.ToString()));
				}
			}
			else
			{
				LoadSavedSearchDiv.Visible = false;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			CollectionSelection.OnSelectionChange += new EventHandler(CollectionSelection_OnSelectionChange);
			CollectionSelection.AutoPostBack = true;
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.SearchButton.Click += new System.EventHandler(this.SearchButton_Click);
			this.ClearFormButton.Click += new System.EventHandler(this.ClearFormButton_Click);
			this.LoadSavedSearchButton.Click += new System.EventHandler(this.LoadSavedSearchButton_Click);
			this.RemoveSavedSearchButton.Click += new System.EventHandler(this.RemoveSavedSearchButton_Click);
			this.RunSavedSearchButton.Click += new System.EventHandler(this.RunSavedSearchButton_Click);
			this.RecentlyAddedSavedSearchButton.Click += new System.EventHandler(this.RecentlyAddedSavedSearchButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void SearchButton_Click(object sender, System.EventArgs e)
		{
			if (!IsValid)
				return;

			Search.SearchParameters parameters = GetSearchOptions();

			if (parameters.conditions.Count == 0)
			{
				parameters.warnings.Add(GetLocalString(this, "NoConditions", "No search conditions were specified."));
			}
			else if (parameters.collections.Count == 0)
			{
				parameters.warnings.Add(GetLocalString(this, "NoCollections", "No collections were specified."));
			}
			else
			{					
				try
				{
					ImageIdentifier[] images = Search.Execute(parameters, Configuration.Instance.GetInt("ui.maxsearchresults"), false);
					if (images == null || images.Length == 0)
						parameters.warnings.Add(GetLocalString(this, "NoImages", "No matching image records were found."));
					else
						Session["LastSearchResult"] = new ResultPageOptions(
							GetLocalString(this, "SearchResults", "Search Results"), 
							"search.aspx", 
							GetLocalString(this, "BackToSearch", "Back to Search"), 
							images);
				}
				catch (TooManySearchResultsException)
				{
					parameters.warnings.Add(GetLocalString(this, "TooManyImages",
						"Too many images match the specified criteria. " +
						"Please change your criteria to be more specific."));
				}
				catch (CoreException ex)
				{
					parameters.warnings.Add(ex.Message);
				}
			}
			if (parameters.warnings.Count == 0)
			{
				string xml = parameters.ToXml();
				Session["LastSearch"] = xml;
				Orciid.Core.User user = Orciid.Core.User.CurrentUser();
				if (user != null && user != AnonymousUser.User
					&& Orciid.Core.User.HasPrivilege(Privilege.UserOptions))
				{
					Properties props = Properties.GetProperties(user);
					if (props != null)
						props.Set("lastsearch", xml);
				}
				Response.Redirect("result.aspx"); 
			}
			else
			{
				foreach (string s in parameters.warnings)
					ShowWarning(s);
			}
		}

		private void PrepareFields()
		{
			ArrayList collections = new ArrayList();
			int[] selected = CollectionSelection.GetSelection();
			if (selected != null)
				foreach (int i in selected)
				{
					Collection coll = Collection.GetByID(i);
					if (coll != null)
						collections.Add(coll);
				}
			SearchCriteriaPanel.Visible = (collections.Count > 0);
			if (collections.Count == 0)
			{
				FieldRepeater.DataSource = null;
			}
			else if (collections.Count == 1)
			{
				ArrayList fields = new ArrayList();
				Collection c = (Collection)collections[0];
				foreach (Field field in c.GetFields())
					if (field.Searchable)
						fields.Add(field);
				FieldRepeater.DataSource = fields;
				ImagesAddedSelection.Visible = c.HasRecordHistory;
				ImagesUpdatedSelection.Visible = c.HasRecordHistory;
			}
			else
			{
				ArrayList dcnames = new ArrayList();
				ArrayList fields = new ArrayList();
				displaylabels = new Hashtable();
				Collection c = (Collection)collections[0];
				foreach (Field field in c.GetFields())
				{
					string dcname = field.DCName != null ? field.DCName.ToLower() : null;
					if (field.Searchable && dcname != null)
					{
						if (!dcnames.Contains(dcname))
						{
							dcnames.Add(dcname);
							fields.Add(field);
						}
						if (displaylabels.ContainsKey(dcname))
						{
							string l = (string)displaylabels[dcname];
							if (l.IndexOf(field.Label) < 0)
								l += "/" + field.Label;
							displaylabels[dcname] = l;
						}
						else
							displaylabels.Add(dcname, field.Label);
					}
				}
				ImagesAddedSelection.Visible = c.HasRecordHistory;
				ImagesUpdatedSelection.Visible = c.HasRecordHistory;
				collections.RemoveAt(0);
				foreach (Collection coll in collections)
				{
					for (int i = dcnames.Count - 1; i >= 0; i--)
					{
						Field f = coll.GetField((string)dcnames[i], true, true);
						if (f == null || !f.Searchable)
						{
							dcnames.RemoveAt(i);
							fields.RemoveAt(i);
						}
						else
						{
							string l = (string)displaylabels[dcnames[i]];
							if (l.IndexOf(f.Label) < 0)
								l += "/" + f.Label;
							displaylabels[dcnames[i]] = l;
						}
					}
					ImagesAddedSelection.Visible = ImagesAddedSelection.Visible && 
						coll.HasRecordHistory;
					ImagesUpdatedSelection.Visible = ImagesUpdatedSelection.Visible &&
						coll.HasRecordHistory;
				}
				FieldRepeater.DataSource = fields;
			}
			FieldRepeater.DataBind();
			if (searchdefaults != null)
			{
				KeywordField.Text = "";
				ImagesAddedDropDownList.SelectedIndex = 0;
				ImagesUpdatedDropDownList.SelectedIndex = 0;
				foreach (SearchCondition condition in searchdefaults.conditions)
				{
					if (condition is KeywordCondition)
					{
						// restore keyword
						if (KeywordField.Text != "")
							KeywordField.Text += " ";
						KeywordField.Text += ((KeywordCondition)condition).Keyword;
					}
					else if (condition is OwnerCondition)
					{
						// owner conditions no longer supported through user interface
					}
					else if (condition is RecordDateCondition)
					{
						// restore record date dropdown boxes
						string mw = ((RecordDateCondition)condition).ModifiedWithin.Days.ToString();
						string cw = ((RecordDateCondition)condition).CreatedWithin.Days.ToString();
						try
						{
							ImagesAddedDropDownList.SelectedValue = cw;
						}
						catch (ArgumentOutOfRangeException)
						{
						}
						try
						{
							ImagesUpdatedDropDownList.SelectedValue = mw;
						}
						catch (ArgumentOutOfRangeException)
						{
						}
					}		
				}			
			}
		}

		protected void FieldRepeater_PlaceHolder_OnDataBinding(object sender, System.EventArgs e)
		{
			PlaceHolder placeholder = sender as PlaceHolder;
			Field field = ((RepeaterItem)placeholder.Parent).DataItem as Field;
			placeholder.Parent.ID = (numSelectedCollections > 1 ? field.DCName : field.Name);
			TextBox textbox = new TextBox();
			textbox.ID = "keyword";
			placeholder.Controls.Add(textbox);
			if (searchdefaults != null)
				foreach (SearchCondition c in searchdefaults.conditions)
					if (c is TextCondition && c.Field != null && 
						((numSelectedCollections == 1 && placeholder.Parent.ID == c.Field.Name) ||
						 (numSelectedCollections > 1 && placeholder.Parent.ID == c.Field.DCElement)))
						textbox.Text = ((TextCondition)c).Keyword;
			if (numSelectedCollections == 1)
			{
				if (field.Type == FieldType.ControlledList && field.ControlledListID > 0)
				{
					placeholder.Controls.Add(new LiteralControl("&nbsp;" + 
						GetLocalString(this, "SelectFromList", "or select from list").Replace(" ", "&nbsp;") + 
						"&nbsp;"));
					DropDownList dropdownlist = new DropDownList();
					dropdownlist.ID = "controlled";
					ControlledList list = ControlledList.GetByID(field.ControlledListID);
					SortedList entries = (list != null ? list.GetSortedList() : new SortedList());
					if (!entries.ContainsKey(""))
						entries.Add("", 0);
					dropdownlist.Items.Clear();
					foreach (string key in entries.Keys)
						dropdownlist.Items.Add(new ListItem(key, entries[key].ToString()));
					dropdownlist.Attributes.Add("onchange",
						String.Format("SearchForm.elements['{0}:keyword'].value=this.options[this.selectedIndex].text",
						placeholder.Parent.UniqueID));
					dropdownlist.EnableViewState = false;
					placeholder.Controls.Add(dropdownlist);
					for (int i = 0; i < dropdownlist.Items.Count; i++)
						if (dropdownlist.Items[i].Text == textbox.Text)
						{
							dropdownlist.SelectedIndex = i;
							break;
						}
				}
				else if (field.Type == FieldType.Date)
				{
					placeholder.Controls.Add(new LiteralControl(" " + GetLocalString(this, "SelectYear", "or select year") + " "));
					DropDownList daterangelist = new DropDownList();
					daterangelist.ID = "range";
					daterangelist.Items.Add(new ListItem(GetLocalString(this, "DateBetween", "between"), "between"));
					daterangelist.Items.Add(new ListItem(GetLocalString(this, "DateBefore", "before"), "before"));
					daterangelist.Items.Add(new ListItem(GetLocalString(this, "DateAfter", "after"), "after"));
					daterangelist.Attributes.Add("onchange",
						String.Format("if (this.options[this.selectedIndex].value != 'between') SearchForm.elements['{0}:date2'].value = ''",
						placeholder.Parent.UniqueID));
					daterangelist.EnableViewState = false;
					placeholder.Controls.Add(daterangelist);
					placeholder.Controls.Add(new LiteralControl(" "));
					TextBox date1box = new TextBox();
					date1box.ID = "date1";
					date1box.Width = new Unit(80);
					date1box.MaxLength = 10;
					placeholder.Controls.Add(date1box);
					RangeValidator date1validator = new RangeValidator();
					date1validator.ControlToValidate = "date1";
					date1validator.Type = ValidationDataType.Integer;
					date1validator.MinimumValue = "-999999999";
					date1validator.MaximumValue = "999999999";
					date1validator.EnableClientScript = true;
					date1validator.Text = " [" + GetLocalString(this, "InvalidYear", "Invalid year") + "] ";
					date1validator.Display = ValidatorDisplay.Dynamic;
					placeholder.Controls.Add(date1validator);
					placeholder.Controls.Add(new LiteralControl(
						"&nbsp;" + GetLocalString(this, "DateBetweenAnd", "and") + "&nbsp;"));
					TextBox date2box = new TextBox();
					date2box.ID = "date2";
					date2box.Width = new Unit(80);
					date2box.MaxLength = 10;
					date2box.Attributes.Add("onchange",
						String.Format("if (SearchForm.elements['{0}:range'].options[SearchForm.elements['{0}:range'].selectedIndex].value != 'between') this.value = ''",
						placeholder.Parent.UniqueID));
					placeholder.Controls.Add(date2box);
					RangeValidator date2validator = new RangeValidator();
					date2validator.ControlToValidate = "date2";
					date2validator.Type = ValidationDataType.Integer;
					date2validator.MinimumValue = "-999999999";
					date2validator.MaximumValue = "999999999";
					date2validator.EnableClientScript = true;
					date2validator.Text = " [" + GetLocalString(this, "InvalidYear", "Invalid year") + "] ";
					date2validator.Display = ValidatorDisplay.Dynamic;
					placeholder.Controls.Add(date2validator);
					if (searchdefaults != null)
						foreach (SearchCondition c in searchdefaults.conditions)
							if (c is DateCondition && c.Field != null && 
								placeholder.Parent.ID == c.Field.Name)
							{
								DateCondition dc = (DateCondition)c;
								switch (dc.Match)
								{
									case DateMatchType.After:
										daterangelist.SelectedIndex = 2;
										if (dc.Start != Int32.MinValue)
											date1box.Text = dc.End.ToString();
										break;
									case DateMatchType.Before:
										daterangelist.SelectedIndex = 1;
										if (dc.Start != Int32.MinValue)
											date1box.Text = dc.Start.ToString();
										break;
									case DateMatchType.Within:
										daterangelist.SelectedIndex = 0;
										if (dc.Start != Int32.MinValue)
											date1box.Text = dc.Start.ToString();
										if (dc.End != Int32.MaxValue)
											date2box.Text = dc.End.ToString();
										break;
								}
							}
				}
			}
		}

		public Search.SearchParameters GetSearchOptions()
		{
			Search.SearchParameters parameters = new Search.SearchParameters();
			int[] selected = CollectionSelection.GetSelection();
			if (selected != null)
				foreach (int i in selected)
				{
					Collection coll = Collection.GetByID(i);
					if (coll != null)
						parameters.collections.Add(coll);
				}

			if (KeywordField.Text.Length > 0)
			{
				foreach (string s in TextCondition.SplitTerms(KeywordField.Text))
				{
					try
					{
						KeywordCondition c = new KeywordCondition();
						c.Keyword = s;
						parameters.conditions.Add(c);
					}
					catch
					{
						parameters.warnings.Add(String.Format(
							GetLocalString(this, "InvalidKeyword", "{0} is not a valid keyword"), s));
					}
				}
			}
			if (parameters.collections.Count == 1)
			{
				foreach (Field field in ((Collection)parameters.collections[0]).GetFields())
					if (field.Searchable)
					{
						Control control = FieldRepeater.FindControl(field.Name);
						if (control != null)
						{
							TextBox input = control.FindControl("keyword") as TextBox;
							if (input != null && input.Text.Length > 0)
							{
								SearchField s = new SearchField();
								s.Name = field.Name;

								bool exactvalue = false;
								bool exactfullvalue = false;

								if (field.Type == FieldType.ControlledList)
								{
									ControlledList list = ControlledList.GetByID(field.ControlledListID);
									if (list != null && list.GetSortedList().ContainsKey(input.Text))
										exactfullvalue = true;
								}
								else if (field.Type == FieldType.ExactText)
									exactvalue = true;

								try
								{
									if (exactvalue || exactfullvalue)
									{
										TextCondition c = new ExactTextCondition(exactfullvalue);
										c.Keyword = input.Text;
										c.Field = s;
										parameters.conditions.Add(c);
									}
									else
									{
										foreach (string k in TextCondition.SplitTerms(input.Text))
										{
											TextCondition c = new TextCondition();
											c.Keyword = k;
											c.Field = s;
											parameters.conditions.Add(c);
										}
									}			
								}
								catch (Exception ex)
								{
									TransactionLog.Instance.AddException("Handled exception", "Error while adding keyword condition.", ex);
									parameters.warnings.Add(String.Format(
										GetLocalString(this, "InvalidKeyword", "{0} is not a valid keyword"), input.Text));
								}
							}									
							if (field.Type == FieldType.Date)
							{
								DropDownList range = control.FindControl("range") as DropDownList;
								TextBox date1 = control.FindControl("date1") as TextBox;
								TextBox date2 = control.FindControl("date2") as TextBox;
								if (range != null && date1 != null && date2 != null &&
									date1.Text.Length > 0)
								{
									SearchField s = new SearchField();
									s.Name = field.Name;
									DateCondition c = new DateCondition();
									c.Field = s;
									switch (range.SelectedItem.Value)
									{
										case "between":
											if (date2.Text != "")
											{
												c.Start = Int32.Parse(date1.Text);
												c.End = Int32.Parse(date2.Text);
												c.Match = DateMatchType.Within;
											}
											break;
										case "before":
											c.Start = Int32.Parse(date1.Text);
											c.Match = DateMatchType.Before;
											break;
										case "after":
											c.End = Int32.Parse(date1.Text);
											c.Match = DateMatchType.After;
											break;
									}
									parameters.conditions.Add(c);
								}
							}
						}
					}
			}
			else
			{
				foreach (Control control in FieldRepeater.Controls)
				{
					TextBox input = control.FindControl("keyword") as TextBox;
					if (input != null && input.Text.Length > 0)
					{
						string[] dcname = control.ID.Split(new char[] {'.'});
						SearchField s = new SearchField();
						s.DCElement = dcname[0];
						if (dcname.Length > 1)
							s.DCRefinement = dcname[1];
						TextCondition c = new TextCondition();
						c.Keyword = input.Text;
						c.Field = s;
						parameters.conditions.Add(c);
					}
				}
			}
			
			RecordDateCondition rc = null;
			if (ImagesAddedSelection.Visible)
			{
				string createdwithin = ImagesAddedDropDownList.SelectedValue;
				if (createdwithin != null && createdwithin.Length > 0)
				{
					if (rc == null)
						rc = new RecordDateCondition();
					rc.CreatedWithin = new TimeSpan(Int32.Parse(createdwithin), 0, 0, 0);
				}
			}
			if (ImagesUpdatedSelection.Visible)
			{
				string modifiedwithin = ImagesUpdatedDropDownList.SelectedValue;
				if (modifiedwithin != null && modifiedwithin.Length > 0)
				{
					if (rc == null)
						rc = new RecordDateCondition();
					rc.ModifiedWithin = new TimeSpan(Int32.Parse(modifiedwithin), 0, 0, 0);
				}
			}
			if (rc != null)
				parameters.conditions.Add(rc);
			return parameters;
		}

		public override string GetHighlightedMenuItem()
		{
			return "Resources_Search";
		}

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return Orciid.Core.User.HasPrivilegeOnAny('C', user, Privilege.ReadCollection);
		}

		private void ClearFormButton_Click(object sender, System.EventArgs e)
		{
			KeywordField.Text = "";
			foreach (Control control in FieldRepeater.Controls)
			{
				TextBox input = control.FindControl("keyword") as TextBox;
				if (input != null)
					input.Text = "";
				DropDownList controlled = control.FindControl("controlled") as DropDownList;
				if (controlled != null)
					controlled.SelectedIndex = 0;
                DropDownList range = control.FindControl("range") as DropDownList;
				if (range != null)
					range.SelectedIndex = 0;
                TextBox date1 = control.FindControl("date1") as TextBox;
				if (date1 != null)
					date1.Text = "";
                TextBox date2 = control.FindControl("date2") as TextBox;
				if (date2 != null)
					date2.Text = "";
			}
		}

		private void RemoveSavedSearchButton_Click(object sender, System.EventArgs e)
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			SavedSearch search = SavedSearch.Get(user, Int32.Parse(SavedSearchDropDownList.SelectedValue));
			if (search != null)
				search.Delete();
			DataBindSavedSearches();
		}

		private void LoadSavedSearchButton_Click(object sender, System.EventArgs e)
		{
			LoadSavedSearch(false);
		}

		private void LoadSavedSearch(bool RecentImages)
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			SavedSearch search = SavedSearch.Get(user, Int32.Parse(SavedSearchDropDownList.SelectedValue));
			if (search != null)
			{
				searchdefaults = search.Parameters;
				if (RecentImages)
				{
					RecordDateCondition cond = new RecordDateCondition();
					cond.CreatedWithin = TimeSpan.FromDays(7);
					searchdefaults.conditions.Add(cond); 
				}
				CollectionSelection.DataSource = GetCollectionEntries();
				CollectionSelection.DataBind();

				int[] s = CollectionSelection.GetSelection();
				numSelectedCollections = (s == null ? 0 : s.Length);

				PrepareFields();
			}
		}

		private void CollectionSelection_OnSelectionChange(object sender, EventArgs e)
		{
			PrepareFields();
		}

		private void RunSavedSearchButton_Click(object sender, System.EventArgs e)
		{
			LoadSavedSearch(false);
			SearchButton_Click(sender, e);
		}

		private void RecentlyAddedSavedSearchButton_Click(object sender, System.EventArgs e)
		{
			LoadSavedSearch(true);
			SearchButton_Click(sender, e);
		}
	}
}
