/// <summary> Constructor for a new instance of the Static_Pages_Builder class </summary>
        /// <param name="Primary_Web_Server_URL"> URL for the primary web server </param>
        /// <param name="Static_Data_Location"> Network location for the data directory </param>
        /// <param name="All_Items_Lookup"> Allows individual items to be retrieved by various methods as <see cref="Application_State.Single_Item"/> objects.</param>
        /// <param name="Code_Manager"> Code manager contains the list of all valid aggregation codes </param>
        /// <param name="HTML_Skin"> HTML Web skin which controls the overall appearance of this digital library </param>
        /// <param name="Icon_Table"> Dictionary of all the wordmark/icons which can be tagged to the items </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        public Static_Pages_Builder(string Primary_Web_Server_URL, string Static_Data_Location,
            Language_Support_Info Translator,
            Aggregation_Code_Manager Code_Manager,
            Item_Lookup_Object All_Items_Lookup,
            Dictionary<string, Wordmark_Icon> Icon_Table,
            SobekCM_Skin_Object HTML_Skin)
        {
            primaryWebServerUrl = Primary_Web_Server_URL;
            staticSobekcmDataLocation = Static_Data_Location;

            tracer = new Custom_Tracer();
            assistant = new SobekCM_Assistant();

               // marcWriter = new MARC_Writer();

            // Save all the objects needed by the UFDC Library
            iconList = Icon_Table;
            translations = Translator;
            codeManager = Code_Manager;
            itemList = All_Items_Lookup;
            ufdcInterface = HTML_Skin;
            dlocInterface = HTML_Skin;

            // Create the mode object
            currentMode = new SobekCM_Navigation_Object
                              {
                                  ViewerCode = "citation",
                                  Skin = "UFDC",
                                  Mode = Display_Mode_Enum.Item_Display,
                                  Language = Web_Language_Enum.English,
                                  Base_URL = primaryWebServerUrl
                              };
        }
        /// <summary> Constructor for a new instance of the Oai_MainWriter class </summary>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Query_String"> URL Query string to parse for OAI-PMH verbs and other values </param>
        public Oai_MainWriter(NameValueCollection Query_String, Item_Lookup_Object All_Items_Lookup)
            : base(null, null, null, null, null,  null, null, null)
        {
            // Build list of valid arguments
            validArgs = new List<string>
                            {
                                "from",
                                "until",
                                "metadataPrefix",
                                "set",
                                "resumptionToken",
                                "identifier",
                                "verb",
                                "portal",
                                "urlrelative"
                            };

            // Load the list of OAI sets
            oaiSets = SobekCM_Database.Get_OAI_Sets();
            queryString = Query_String;

            itemLookupObj = All_Items_Lookup;

            root = SobekCM_Library_Settings.Base_Data_Directory;
        }
 /// <summary> Constructor for a new instance of the Search_Results_HtmlSubwriter class </summary>
 /// <param name="Results_Statistics"> Information about the entire set of results for a search or browse </param>
 /// <param name="Paged_Results"> Single page of results for a search or browse, within the entire set </param>
 /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
 /// <param name="Translator"> Language support object which handles simple translational duties </param>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 /// <param name="Current_User"> Currently logged on user </param>
 public Search_Results_HtmlSubwriter(Search_Results_Statistics Results_Statistics,
     List<iSearch_Title_Result> Paged_Results,
     Aggregation_Code_Manager Code_Manager, Language_Support_Info Translator,
     Item_Lookup_Object All_Items_Lookup, 
     User_Object Current_User)
 {
     currentUser = Current_User;
     pagedResults = Paged_Results;
     resultsStatistics = Results_Statistics;
     translations = Translator;
     codeManager = Code_Manager;
     allItemsTable = All_Items_Lookup;
 }
 /// <summary> Constructor for a new instance of the Json_MainWriter class </summary>
 /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
 /// <param name="Hierarchy_Object"> Current item aggregation object to display </param>
 /// <param name="Results_Statistics"> Information about the entire set of results for a search or browse </param>
 /// <param name="Paged_Results"> Single page of results for a search or browse, within the entire set </param>
 /// <param name="Browse_Object"> Object contains all the basic information about any browse or info display </param>
 /// <param name="Current_Item"> Current item to display </param>
 /// <param name="Current_Page"> Current page within the item</param>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 /// <param name="Current_Image_Root"> Current root directory to pull images and metadata for digital resources </param>
 public Json_MainWriter(SobekCM_Navigation_Object Current_Mode,
     Item_Aggregation Hierarchy_Object,
     Search_Results_Statistics Results_Statistics,
     List<iSearch_Title_Result> Paged_Results,
     Item_Aggregation_Browse_Info Browse_Object,
     SobekCM_Item Current_Item,
     Page_TreeNode Current_Page,
     Item_Lookup_Object All_Items_Lookup,
     string Current_Image_Root)
     : base(Current_Mode, Hierarchy_Object, Results_Statistics, Paged_Results, Browse_Object,   Current_Item, Current_Page, null)
 {
     allItems = All_Items_Lookup;
     currentGreenstoneImageRoot = Current_Image_Root;
 }
 /// <summary> Constructor for a new instance of the DataSet_Browse_Info_AggregationViewer class </summary>
 /// <param name="Browse_Object"> Browse or information object to be displayed </param>
 /// <param name="Results_Statistics"> Information about the entire set of results for a search or browse </param>
 /// <param name="Paged_Results"> Single page of results for a search or browse, within the entire set </param>
 /// <param name="Code_Manager"> Code manager object maintains mapping between SobekCM codes and greenstone codes (used by result_dataset_html_subwriter)</param>
 /// <param name="Item_List"> Object for pulling additional information about each item during display </param>
 /// <param name="Current_User"> Currently logged on user, or NULL </param>
 public DataSet_Browse_Info_AggregationViewer(Item_Aggregation_Browse_Info Browse_Object,
     Search_Results_Statistics Results_Statistics,
     List<iSearch_Title_Result> Paged_Results,
     Aggregation_Code_Manager Code_Manager,
     Item_Lookup_Object Item_List,
     User_Object Current_User)
     : base(null, null)
 {
     browseObject = Browse_Object;
     codeManager = Code_Manager;
     itemList = Item_List;
     currentUser = Current_User;
     resultsStatistics = Results_Statistics;
     pagedResults = Paged_Results;
 }
        /// <summary> Constructor for a new instance of the SobekCM_Navigation_Object which stores 
        /// all of the information about an individual request. </summary>
        /// <param name="QueryString">Query string information for analysis</param>
        /// <param name="Base_URL"> Requested base URL (without query string, etc..)</param>
        /// <param name="User_Languages"> Languages preferred by user, per their browser settings </param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections </param>
        /// <param name="Aggregation_Aliases"> List of all existing aliases for existing aggregations</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library</param>
        /// <param name="URL_Portals"> List of all web portals into this system </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        public SobekCM_Navigation_Object(NameValueCollection QueryString, string Base_URL, string[] User_Languages, Aggregation_Code_Manager Code_Manager, Dictionary<string, string> Aggregation_Aliases, ref Item_Lookup_Object All_Items_Lookup, Portal_List URL_Portals, Custom_Tracer Tracer )
        {
            // Do general item construction
            Constructor_Helper();

            // If there is a mode value or an aggregation value, use the legacy query string analyzer
            if ((QueryString["m"] != null) || (QueryString["a"] != null) || (QueryString["c"] != null) || (QueryString["s"] != null) || (QueryString["g"] != null) || (QueryString["h"] != null) || (QueryString["i"] != null))
            {
                // Use the legacy query string analyzer
                SobekCM_QueryString_Analyzer_Legacy analyzerLegacy = new SobekCM_QueryString_Analyzer_Legacy();
                analyzerLegacy.Parse_Query(QueryString, this, Base_URL, User_Languages, Code_Manager, Aggregation_Aliases, ref All_Items_Lookup, URL_Portals, Tracer);
            }
            else
            {
                // Analyze the query string with the default analyzer
                SobekCM_QueryString_Analyzer analyzer = new SobekCM_QueryString_Analyzer();
                analyzer.Parse_Query(QueryString, this, Base_URL, User_Languages, Code_Manager, Aggregation_Aliases, ref All_Items_Lookup, URL_Portals, Tracer);
            }
        }
        /// <summary> Constructor for a new instance of the Full_ResultsViewer class </summary>
        /// <param name="CurrentMode"> Sobek object that holds useful information </param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        public Google_Map_ResultsViewer_Beta(SobekCM_Navigation_Object CurrentMode, Item_Lookup_Object All_Items_Lookup)
        {
            //create new tracer?
            Custom_Tracer Tracer = new Custom_Tracer();

            base.All_Items_Lookup = All_Items_Lookup;

            //holds actions from page
            string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;

            // See if there were hidden requests
            if (!String.IsNullOrEmpty(payload))
            {
                //if (action == "action")
                    Perform_Callback_Action(payload, Tracer);
            }
            else
            {
                //do a search for all the items in this agg
                string temp_AggregationId = CurrentMode.Aggregation;
                string[] temp_AggregationList = temp_AggregationId.Split(' ');
                Perform_Aggregation_Search(temp_AggregationList, Tracer);
            }
        }
        /// <summary> Verifies that each global object is built and builds them upon request </summary>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        /// <param name="Reload_All"> Flag indicates if everything should be reloaded/repopulated</param>
        /// <param name="Skins"> [REF] Collection of all the web skins </param>
        /// <param name="Translator"> [REF] Language support object which handles simple translational duties </param>
        /// <param name="Code_Manager"> [REF] List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Icon_Dictionary"> [REF] Dictionary of information about every wordmark/icon in this digital library </param>
        /// <param name="Stats_Date_Range"> [REF] Object contains the start and end dates for the statistical data in the database </param>
        /// <param name="Thematic_Headings"> [REF] Headings under which all the highlighted collections on the main home page are organized </param>
        /// <param name="Aggregation_Aliases"> [REF] List of all existing aliases for existing aggregations </param>
        /// <param name="IP_Restrictions"> [REF] List of all IP Restriction ranges in use by this digital library </param>
        /// <param name="URL_Portals"> [REF] List of all web portals into this system </param>
        /// <param name="Mime_Types">[REF] Dictionary of MIME types by extension</param>
        public static void Build_Application_State(Custom_Tracer Tracer, bool Reload_All,
            ref SobekCM_Skin_Collection Skins, ref Language_Support_Info Translator,
            ref Aggregation_Code_Manager Code_Manager, ref Item_Lookup_Object All_Items_Lookup,
            ref Dictionary<string, Wordmark_Icon> Icon_Dictionary, 
            ref Statistics_Dates Stats_Date_Range, 
            ref List<Thematic_Heading> Thematic_Headings,
            ref Dictionary<string, string> Aggregation_Aliases, 
            ref IP_Restriction_Ranges IP_Restrictions,
            ref Portal_List URL_Portals,
            ref Dictionary<string, Mime_Type_Info> Mime_Types,
			ref List<string> Item_Viewer_Priority )
        {
            // Should we reload the data from the exteral configuraiton file?
            if (Reload_All)
            {
                SobekCM_Library_Settings.Read_Configuration_File();
                if ( SobekCM_Library_Settings.Database_Connections.Count > 0 )
                    SobekCM_Database.Connection_String = SobekCM_Library_Settings.Database_Connections[0].Connection_String;
                SobekCM_Library_Settings.Refresh(SobekCM_Database.Get_Settings_Complete(null));
            }

            // If there is no database connection string, there is a problem
            if ((SobekCM_Library_Settings.Database_Connections.Count == 0) || (String.IsNullOrEmpty(SobekCM_Library_Settings.Database_Connections[0].Connection_String)))
            {
                throw new ApplicationException("Missing database connection string!");
            }

            // Set the database connection strings
            Resource_Object.Database.SobekCM_Database.Connection_String = SobekCM_Library_Settings.Database_Connections[0].Connection_String;
            SobekCM_Database.Connection_String = SobekCM_Library_Settings.Database_Connections[0].Connection_String;

            // Set the workflow and disposition types
            if ((SobekCM_Library_Settings.Need_Workflow_And_Disposition_Types) || ( Reload_All ))
            {
                SobekCM_Library_Settings.Set_Workflow_And_Disposition_Types(SobekCM_Database.All_WorkFlow_Types, SobekCM_Database.All_Possible_Disposition_Types);
            }

            // Set the metadata types
            if ((SobekCM_Library_Settings.Need_Metadata_Types) || ( Reload_All ))
            {
                SobekCM_Library_Settings.Set_Metadata_Types(SobekCM_Database.Get_Metadata_Fields(null) );
            }

            // Set the search stop words
            if ((SobekCM_Library_Settings.Need_Search_Stop_Words) || (Reload_All))
            {
                SobekCM_Library_Settings.Search_Stop_Words = SobekCM_Database.Search_Stop_Words(Tracer);
            }

            // Check the list of thematic headings
            if ((Thematic_Headings == null) || (Reload_All))
            {
                if (Thematic_Headings != null)
                {
                    lock (Thematic_Headings)
                    {
                        if (!SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer))
                        {
                            Thematic_Headings = null;
                            throw SobekCM_Database.Last_Exception;
                        }
                    }
                }
                else
                {
                    Thematic_Headings = new List<Thematic_Heading>();
                    if (!SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer))
                    {
                        Thematic_Headings = null;
                        throw SobekCM_Database.Last_Exception;
                    }
                }
            }

            // Check the list of forwardings
            if ((Aggregation_Aliases == null) || (Reload_All))
            {
                if (Aggregation_Aliases != null)
                {
                    lock (Aggregation_Aliases)
                    {
                        SobekCM_Database.Populate_Aggregation_Aliases(Aggregation_Aliases, Tracer);
                    }
                }
                else
                {
                    Aggregation_Aliases = new Dictionary<string, string>();
                    SobekCM_Database.Populate_Aggregation_Aliases(Aggregation_Aliases, Tracer);
                }
            }

            // Check the list of constant skins
            if ((Skins == null) || (Skins.Count == 0) || (Reload_All))
            {
                if (Skins != null)
                {
                    lock (Skins)
                    {
                        SobekCM_Skin_Collection_Builder.Populate_Default_Skins(Skins, Tracer);
                    }
                }
                else
                {
                    Skins = new SobekCM_Skin_Collection();
                    SobekCM_Skin_Collection_Builder.Populate_Default_Skins(Skins, Tracer);
                }
            }

            // Check the list of all web portals
            if ((URL_Portals == null) || (URL_Portals.Count == 0) || (Reload_All))
            {
                if (URL_Portals != null)
                {
                    lock (URL_Portals)
                    {
                        SobekCM_Database.Populate_URL_Portals(URL_Portals, Tracer);
                    }
                }
                else
                {
                    URL_Portals = new Portal_List();
                    SobekCM_Database.Populate_URL_Portals(URL_Portals, Tracer);
                }
            }

            // Check the translation table has been loaded
            if (( Translator == null) || (Reload_All))
            {
                // Get the translation hashes into memory
                if (Translator != null)
                {
                    lock (Translator)
                    {
                        SobekCM_Database.Populate_Translations(Translator, Tracer);
                    }
                }
                else
                {
                    Translator = new Language_Support_Info();
                    SobekCM_Database.Populate_Translations(Translator, Tracer);
                }
            }

            // Check that the conversion from SobekCM Codes to Greenstone Codes has been loaded
            if ((Code_Manager == null) || (Reload_All))
            {
                if (Code_Manager != null)
                {
                    lock (Code_Manager)
                    {
                        SobekCM_Database.Populate_Code_Manager(Code_Manager, Tracer);
                    }
                }
                else
                {
                    Code_Manager = new Aggregation_Code_Manager();
                    SobekCM_Database.Populate_Code_Manager(Code_Manager, Tracer);
                }
            }

            // Check the statistics date range information
            if ((Stats_Date_Range == null) || (Reload_All))
            {
                if (Stats_Date_Range != null)
                {
                    // Get the translation hashes into memory
                    lock (Stats_Date_Range)
                    {
                        SobekCM_Database.Populate_Statistics_Dates(Stats_Date_Range, Tracer);
                    }
                }
                else
                {
                    Stats_Date_Range = new Statistics_Dates();
                    SobekCM_Database.Populate_Statistics_Dates(Stats_Date_Range, Tracer);
                }
            }

            // Get the Icon list
            if ((Icon_Dictionary == null) || ( Reload_All ))
            {
                if (Icon_Dictionary != null)
                {
                    // Get the translation hashes into memory
                    lock (Icon_Dictionary)
                    {
                        SobekCM_Database.Populate_Icon_List(Icon_Dictionary, Tracer);
                    }
                }
                else
                {
                    Icon_Dictionary = new Dictionary<string, Wordmark_Icon>();
                    SobekCM_Database.Populate_Icon_List(Icon_Dictionary, Tracer);
                }
            }

            // Check the list of ip range restrictions
            if ((IP_Restrictions == null) || (Reload_All))
            {
                if (IP_Restrictions != null)
                {
                    lock (IP_Restrictions)
                    {
                        DataTable ipRestrictionTbl = SobekCM_Database.Get_IP_Restriction_Ranges(Tracer);
                        if (ipRestrictionTbl != null)
                        {
                            IP_Restrictions.Populate_IP_Ranges(ipRestrictionTbl);
                        }
                    }
                }
                else
                {
                    DataTable ipRestrictionTbl = SobekCM_Database.Get_IP_Restriction_Ranges(Tracer);
                    if (ipRestrictionTbl != null)
                    {
                        IP_Restrictions = new IP_Restriction_Ranges();
                        IP_Restrictions.Populate_IP_Ranges(ipRestrictionTbl);
                    }
                }
            }

            // Get the MIME type list
            if ((Mime_Types == null) || (Reload_All))
            {
                if (Mime_Types != null)
                {
                    // Get the translation hashes into memory
                    lock (Mime_Types)
                    {
                        SobekCM_Database.Populate_MIME_List(Mime_Types, Tracer);
                    }
                }
                else
                {
                    Mime_Types = new Dictionary<string, Mime_Type_Info>();
                    SobekCM_Database.Populate_MIME_List(Mime_Types, Tracer);
                }
            }

            // Check the list of forwardings
            if ((Item_Viewer_Priority == null) || (Reload_All))
            {
                if (Item_Viewer_Priority != null)
                {
                    lock (Item_Viewer_Priority)
                    {
                        Item_Viewer_Priority = SobekCM_Database.Get_Viewer_Priority(Tracer);
                    }
                }
                else
                {
                    Item_Viewer_Priority = SobekCM_Database.Get_Viewer_Priority(Tracer);
                }
            }

            // Check the IE hack CSS is loaded
            if ((HttpContext.Current.Application["NonIE_Hack_CSS"] == null) || (Reload_All))
            {
                string css_file = HttpContext.Current.Server.MapPath("default/SobekCM_NonIE.css");
                if (File.Exists(css_file))
                {
                    try
                    {
                        StreamReader reader = new StreamReader(css_file);
                        HttpContext.Current.Application["NonIE_Hack_CSS"] = reader.ReadToEnd().Trim();
                        reader.Close();
                    }
                    catch (Exception)
                    {
                        HttpContext.Current.Application["NonIE_Hack_CSS"] = "/* ERROR READING FILE: default/SobekCM_NonIE.css */";
                        throw;
                    }
                }
                else
                {
                    HttpContext.Current.Application["NonIE_Hack_CSS"] = String.Empty;
                }
            }
        }
        /// <summary> Constructor for a new instance of the Delete_Item_MySobekViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="All_Items_Lookup"> Allows individual items to be retrieved by various methods as <see cref="SobekCM.Library.Application_State.Single_Item"/> objects.</param>
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        public Delete_Item_MySobekViewer(User_Object User,
            SobekCM_Navigation_Object Current_Mode, 
            Item_Lookup_Object All_Items_Lookup,
            
            Custom_Tracer Tracer)
            : base(User)
        {
            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Delete this item");

            // Save mode and set defaults
            currentMode = Current_Mode;
            errorCode = -1;

            // First, ensure this is a logged on user and system administrator before continuing
            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Validate user permissions" );
            if ((User == null) || ((!User.Is_System_Admin) && (User.UserName.ToLower() != "neldamaxs")))
            {
                Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "User does not have delete permissions", Custom_Trace_Type_Enum.Error );
                errorCode = 1;
            }

            // Second, ensure the item is valid
            if( errorCode == -1 )
            {
                Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Validate item exists" );
                if (!All_Items_Lookup.Contains_BibID_VID( Current_Mode.BibID, Current_Mode.VID))
                {
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Item indicated is not valid", Custom_Trace_Type_Enum.Error );
                    errorCode = 2;
                }
            }

            // Get the current item details
            string bib_location = String.Empty;
            string vid_location = String.Empty;
            if ( errorCode == -1 )
            {
                // Get item details
                DataSet itemDetails = SobekCM_Database.Get_Item_Details(currentMode.BibID, currentMode.VID, Tracer);

                // If the itemdetails was null, this item is somehow invalid item then
                if ( itemDetails == null )
                {
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Item indicated is not valid", Custom_Trace_Type_Enum.Error );
                    errorCode = 2;
                }
                else
                {
                    // Get the location for this METS file from the returned value
                    DataRow mainItemRow = itemDetails.Tables[2].Rows[0];
                    bib_location = SobekCM_Library_Settings.Image_Server_Network + mainItemRow["File_Location"].ToString().Replace("/", "\\");
                    vid_location = bib_location + "\\" + currentMode.VID;
                }
            }

             // If this is a postback, handle any events first
            if ((currentMode.isPostBack) && ( errorCode < 0 ))
            {
                Debug.Assert(User != null, "User != null");

                // Pull the standard values
                string save_value = HttpContext.Current.Request.Form["admin_delete_item"];
                string text_value = HttpContext.Current.Request.Form["admin_delete_confirm"];

                // Better say "DELETE", or just send back to the item
                if (( save_value == null ) || ( save_value.ToUpper() != "DELETE" ) || ( text_value.ToUpper() != "DELETE"))
                {
                    HttpContext.Current.Response.Redirect(Current_Mode.Base_URL + currentMode.BibID + "/" + currentMode.VID);
                }
                else
                {
                    errorCode = 0;

                    // Perform the database delete
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Perform database update");
                    bool database_result = SobekCM_Database.Delete_SobekCM_Item(currentMode.BibID, currentMode.VID, User.Is_System_Admin, String.Empty );

                    if (!database_result)
                    {
                        Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Error performing delete in the database", Custom_Trace_Type_Enum.Error);
                        errorCode = 3;
                    }
                    else
                    {
                        // Move the folder to deletes
                        try
                        {
                            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Move resource files to DELETED folder");

                            // Make sure upper deleted folder exists, or create it
                            string delete_folder = SobekCM_Library_Settings.Image_Server_Network + "DELETED";
                            if (!Directory.Exists(delete_folder))
                                Directory.CreateDirectory(delete_folder);

                            // Create the bib level folder next
                            string bib_folder = SobekCM_Library_Settings.Image_Server_Network + "DELETED\\" + currentMode.BibID;
                            if (!Directory.Exists(bib_folder))
                                Directory.CreateDirectory(bib_folder);

                            // Ensure the VID folder does not exist
                            string vid_folder = SobekCM_Library_Settings.Image_Server_Network + "DELETED\\" + currentMode.BibID + "\\" + currentMode.VID;
                            if (Directory.Exists(vid_folder))
                                Directory.Move(vid_folder, vid_folder + "_OLD");

                            // Move the VID folder over now
                            Directory.Move(vid_location, vid_folder);

                            // Check if this was the last VID under this BIB
                            if (Directory.GetDirectories(bib_location).Length == 0)
                            {
                                // Move all files over to the bib folder then
                                string[] bib_files = Directory.GetFiles(bib_location);
                                foreach (string thisFile in bib_files)
                                {
                                    string fileName = (new FileInfo(thisFile)).Name;
                                    string new_file = bib_folder + "\\" + fileName;
                                    File.Move(thisFile, new_file);
                                }
                            }
                        }
                        catch (Exception ee)
                        {
                            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Error moving the folder and files to the DELETED folder", Custom_Trace_Type_Enum.Error);
                            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", ee.Message, Custom_Trace_Type_Enum.Error);
                            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", ee.StackTrace, Custom_Trace_Type_Enum.Error);
                            errorCode = 4;
                        }

                        // Remove from the item list
                        All_Items_Lookup.Remove_Item(currentMode.BibID, currentMode.VID);

                        // Also remove from the cache
                        Cached_Data_Manager.Remove_Digital_Resource_Object(currentMode.BibID, currentMode.VID, Tracer);
                    }
                }
            }
        }
 /// <summary> Constructor for a new instance of the Bookshelf_View_ResultsViewer class </summary>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 /// <param name="Current_User"> Current user object </param>
 public Bookshelf_View_ResultsViewer(Item_Lookup_Object All_Items_Lookup, User_Object Current_User )
 {
     base.All_Items_Lookup = All_Items_Lookup;
     currentUser = Current_User;
 }
        /// <summary> Constructor for a new instance of the Text_MainWriter class </summary>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="Hierarchy_Object"> Current item aggregation object to display </param>
        /// <param name="Results_Statistics"> Information about the entire set of results for a search or browse </param>
        /// <param name="Paged_Results"> Single page of results for a search or browse, within the entire set </param>
        /// <param name="Browse_Object"> Object contains all the basic information about any browse or info display </param>
        /// <param name="Current_Item"> Current item to display </param>
        /// <param name="Current_Page"> Current page within the item</param>
        /// <param name="HTML_Skin"> HTML Web skin which controls the overall appearance of this digital library </param>
        /// <param name="Current_User"> Currently logged on user </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="Item_List"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Stats_Date_Range"> Object contains the start and end dates for the statistical data in the database </param>
        /// <param name="Search_History"> List of recent searches performed against this digital library </param>
        /// <param name="Icon_Dictionary"> Dictionary of information about every wordmark/icon in this digital library, used to build the wordmarks subpage </param>
        /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the main home page are organized </param>
        /// <param name="Public_Folder"> Object contains the information about the public folder to display </param>
        /// <param name="Aggregation_Aliases"> List of all existing aliases for existing aggregations </param>
        /// <param name="Web_Skin_Collection"> Collection of all the web skins </param>
        /// <param name="Checked_Items"> List of all items which are currently checked out for single fair use and the IP address currently viewing the item</param>
        /// <param name="IP_Restrictions"> Any possible restriction on item access by IP ranges </param>
        /// <param name="URL_Portals"> List of all web portals into this system </param>
        /// <param name="Site_Map"> Optional site map object used to render a navigational tree-view on left side of static web content pages </param>
        /// <param name="Items_In_Title"> List of items within the current title ( used for the Item Group display )</param>
        /// <param name="Static_Web_Content"> HTML content-based browse, info, or imple CMS-style web content objects.  These are objects which are read from a static HTML file and much of the head information must be maintained </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        public Html_MainWriter(SobekCM_Navigation_Object Current_Mode,
            Item_Aggregation Hierarchy_Object,
            Search_Results_Statistics Results_Statistics,
            List<iSearch_Title_Result> Paged_Results,
            Item_Aggregation_Child_Page Browse_Object,
            SobekCM_Item Current_Item,
            Page_TreeNode Current_Page,
            SobekCM_Skin_Object HTML_Skin,
            User_Object Current_User,
            Language_Support_Info Translator,
            Aggregation_Code_Manager Code_Manager,
            Item_Lookup_Object Item_List,
            Statistics_Dates Stats_Date_Range,
            Recent_Searches Search_History,
            Dictionary<string, Wordmark_Icon> Icon_Dictionary,
            List<Thematic_Heading> Thematic_Headings,
            Public_User_Folder Public_Folder,
            Dictionary<string, string> Aggregation_Aliases,
            SobekCM_Skin_Collection Web_Skin_Collection,
            Checked_Out_Items_List Checked_Items,
            IP_Restriction_Ranges IP_Restrictions,
            Portal_List URL_Portals,
            SobekCM_SiteMap Site_Map,
            SobekCM_Items_In_Title Items_In_Title,
            HTML_Based_Content Static_Web_Content,
            Custom_Tracer Tracer )
            : base(Current_Mode, Hierarchy_Object, Results_Statistics, Paged_Results, Browse_Object,  Current_Item, Current_Page, Static_Web_Content)
        {
            // Save parameters
            htmlSkin = HTML_Skin;
            translator = Translator;
            codeManager = Code_Manager;
            itemList = Item_List;
            statsDateRange = Stats_Date_Range;
            searchHistory = Search_History;
            currentUser = Current_User;
            iconList = Icon_Dictionary;
            thematicHeadings = Thematic_Headings;
            publicFolder = Public_Folder;
            aggregationAliases = Aggregation_Aliases;
            webSkins = Web_Skin_Collection;
            checkedItems = Checked_Items;
            ipRestrictionInfo = IP_Restrictions;
            urlPortals = URL_Portals;
            siteMap = Site_Map;
            itemsInTitle = Items_In_Title;

            // Set some defaults

            // Handle basic events which may be fired by the internal header
            if (HttpContext.Current.Request.Form["internal_header_action"] != null)
            {
                // Pull the action value
                string internalHeaderAction = HttpContext.Current.Request.Form["internal_header_action"].Trim();

                // Was this to hide or show the header?
                if ((internalHeaderAction == "hide") || (internalHeaderAction == "show"))
                {
                    // Pull the current visibility from the session
                    bool shown = !((HttpContext.Current.Session["internal_header"] != null) && (HttpContext.Current.Session["internal_header"].ToString() == "hidden"));
                    if ((internalHeaderAction == "hide") && (shown))
                    {
                        HttpContext.Current.Session["internal_header"] = "hidden";
                        currentMode.Redirect();
                        return;
                    }
                    if ((internalHeaderAction == "show") && (!shown))
                    {
                        HttpContext.Current.Session["internal_header"] = "shown";
                        currentMode.Redirect();
                        return;
                    }
                }
            }

            try
            {

                // Create the html sub writer now
                switch (Current_Mode.Mode)
                {
                    case Display_Mode_Enum.Internal:
                        subwriter = new Internal_HtmlSubwriter(iconList, currentUser, codeManager);
                        break;

                    case Display_Mode_Enum.Statistics:
                        subwriter = new Statistics_HtmlSubwriter(searchHistory, codeManager, statsDateRange);
                        break;

                    case Display_Mode_Enum.Preferences:
                        subwriter = new Preferences_HtmlSubwriter(currentMode);
                        break;

                    case Display_Mode_Enum.Error:
                        subwriter = new Error_HtmlSubwriter(false);
                        // Send the email now
                        if (currentMode.Caught_Exception != null)
                        {
                            if (currentMode.Error_Message.Length == 0)
                                currentMode.Error_Message = "Unknown exception caught";
                            Email_Information(currentMode.Error_Message, currentMode.Caught_Exception, Tracer, false);
                        }
                        break;

                    case Display_Mode_Enum.Legacy_URL:
                        subwriter = new LegacyUrl_HtmlSubwriter();
                        break;

                    case Display_Mode_Enum.Item_Print:
                        subwriter = new Print_Item_HtmlSubwriter(currentItem, codeManager, translator, currentMode);
                        break;

                    case Display_Mode_Enum.Contact:

                        StringBuilder builder = new StringBuilder();
                        builder.Append("\n\nSUBMISSION INFORMATION\n");
                        builder.Append("\tDate:\t\t\t\t" + DateTime.Now.ToString() + "\n");
                        string lastMode = String.Empty;
                        try
                        {
                            if (HttpContext.Current.Session["Last_Mode"] != null)
                                lastMode = HttpContext.Current.Session["Last_Mode"].ToString();
                            builder.Append("\tIP Address:\t\t\t" + HttpContext.Current.Request.UserHostAddress + "\n");
                            builder.Append("\tHost Name:\t\t\t" + HttpContext.Current.Request.UserHostName + "\n");
                            builder.Append("\tBrowser:\t\t\t" + HttpContext.Current.Request.Browser.Browser + "\n");
                            builder.Append("\tBrowser Platform:\t\t" + HttpContext.Current.Request.Browser.Platform + "\n");
                            builder.Append("\tBrowser Version:\t\t" + HttpContext.Current.Request.Browser.Version + "\n");
                            builder.Append("\tBrowser Language:\t\t");
                            bool first = true;
                            string[] languages = HttpContext.Current.Request.UserLanguages;
                            if (languages != null)
                                foreach (string thisLanguage in languages)
                                {
                                    if (first)
                                    {
                                        builder.Append(thisLanguage);
                                        first = false;
                                    }
                                    else
                                    {
                                        builder.Append(", " + thisLanguage);
                                    }
                                }

                            builder.Append("\n\nHISTORY\n");
                            if (HttpContext.Current.Session["LastSearch"] != null)
                                builder.Append("\tLast Search:\t\t" + HttpContext.Current.Session["LastSearch"] + "\n");
                            if (HttpContext.Current.Session["LastResults"] != null)
                                builder.Append("\tLast Results:\t\t" + HttpContext.Current.Session["LastResults"] + "\n");
                            if (HttpContext.Current.Session["Last_Mode"] != null)
                                builder.Append("\tLast Mode:\t\t\t" + HttpContext.Current.Session["Last_Mode"] + "\n");
                            builder.Append("\tURL:\t\t\t\t" + HttpContext.Current.Items["Original_URL"]);
                        }
                        catch
                        {

                        }
                        subwriter = new Contact_HtmlSubwriter(lastMode, builder.ToString(), currentMode, hierarchyObject);
                        break;

                    case Display_Mode_Enum.Contact_Sent:
                        subwriter = new Contact_HtmlSubwriter(String.Empty, String.Empty, currentMode, hierarchyObject);
                        break;

                    case Display_Mode_Enum.Simple_HTML_CMS:
                        subwriter = new Web_Content_HtmlSubwriter(hierarchyObject, currentMode, htmlSkin, htmlBasedContent, siteMap);
                        break;

                    case Display_Mode_Enum.My_Sobek:
                        subwriter = new MySobek_HtmlSubwriter(results_statistics, paged_results, codeManager, itemList, hierarchyObject, htmlSkin, translator, currentMode, currentItem, currentUser, iconList, statsDateRange, webSkins, Tracer);
                        break;

                    case Display_Mode_Enum.Administrative:
                        subwriter = new Admin_HtmlSubwriter(codeManager, itemList, hierarchyObject, htmlSkin, translator, currentMode, aggregationAliases, webSkins, currentUser, ipRestrictionInfo, iconList, urlPortals, thematicHeadings, Tracer);
                        break;

                    case Display_Mode_Enum.Results:
                        subwriter = new Search_Results_HtmlSubwriter(results_statistics, paged_results, codeManager, translator, itemList, currentUser);
                        break;

                    case Display_Mode_Enum.Public_Folder:
                        subwriter = new Public_Folder_HtmlSubwriter(results_statistics, paged_results, codeManager, translator, itemList, currentUser, publicFolder);
                        break;

                    case Display_Mode_Enum.Search:
                    case Display_Mode_Enum.Aggregation:
                        subwriter = new Aggregation_HtmlSubwriter(hierarchyObject, currentMode, htmlSkin, translator, thisBrowseObject, results_statistics, paged_results, codeManager, itemList, thematicHeadings, currentUser, htmlBasedContent, Tracer);
                        break;

                    case Display_Mode_Enum.Item_Display:
                        if ((!currentMode.Invalid_Item) && (currentItem != null))
                        {
                            bool show_toc = false;
                            if (HttpContext.Current.Session["Show TOC"] != null)
                            {
                                Boolean.TryParse(HttpContext.Current.Session["Show TOC"].ToString(), out show_toc);
                            }

                            // Check that this item is not checked out by another user
                            bool itemCheckedOutByOtherUser = false;
                            if (currentItem.Behaviors.CheckOut_Required)
                            {
                                if (!checkedItems.Check_Out(currentItem.Web.ItemID, HttpContext.Current.Request.UserHostAddress))
                                {
                                    itemCheckedOutByOtherUser = true;
                                }
                            }

                            // Check to see if this is IP restricted
                            string restriction_message = String.Empty;
                            if (currentItem.Behaviors.IP_Restriction_Membership > 0)
                            {
                                if (HttpContext.Current != null)
                                {
                                    int user_mask = (int)HttpContext.Current.Session["IP_Range_Membership"];
                                    int comparison = currentItem.Behaviors.IP_Restriction_Membership & user_mask;
                                    if (comparison == 0)
                                    {
                                        int restriction = currentItem.Behaviors.IP_Restriction_Membership;
                                        int restriction_counter = 0;
                                        while (restriction % 2 != 1)
                                        {
                                            restriction = restriction >> 1;
                                            restriction_counter++;
                                        }
                                        restriction_message = ipRestrictionInfo[restriction_counter].Item_Restricted_Statement;
                                    }
                                }
                            }

                            // Create the item viewer writer
                            subwriter = new Item_HtmlSubwriter(currentItem, currentPage, currentUser, codeManager, translator, show_toc, (SobekCM_Library_Settings.JP2ServerUrl.Length > 0), currentMode, hierarchyObject, restriction_message, itemsInTitle, Tracer);
                            ((Item_HtmlSubwriter)subwriter).Item_Checked_Out_By_Other_User = itemCheckedOutByOtherUser;
                        }
                        else
                        {
                            // Create the invalid item html subwrite and write the HTML
                            subwriter = new Error_HtmlSubwriter(true);
                        }
                        break;

                }
            }
            catch (Exception ee)
            {
                // Send to the dashboard
                if ((HttpContext.Current.Request.UserHostAddress == "127.0.0.1") || (HttpContext.Current.Request.UserHostAddress == HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]) || (HttpContext.Current.Request.Url.ToString().IndexOf("localhost") >= 0))
                {
                    Tracer.Add_Trace("Html_MainWriter.Constructor", "Exception caught!", Custom_Trace_Type_Enum.Error);
                    Tracer.Add_Trace("Html_MainWriter.Constructor", ee.Message, Custom_Trace_Type_Enum.Error);
                    Tracer.Add_Trace("Html_MainWriter.Constructor", ee.StackTrace, Custom_Trace_Type_Enum.Error);

                    // Wrap this into the SobekCM Exception
                    SobekCM_Traced_Exception newException = new SobekCM_Traced_Exception("Exception caught while building the mode-specific HTML Subwriter", ee, Tracer);

                    // Save this to the session state, and then forward to the dashboard
                    HttpContext.Current.Session["Last_Exception"] = newException;
                    HttpContext.Current.Response.Redirect("dashboard.aspx", false);
                    Current_Mode.Request_Completed = true;

                    return;
                }
                else
                {
                    subwriter = new Error_HtmlSubwriter(false);
                }
            }

            if (subwriter != null)
            {
                subwriter.Mode = currentMode;
                subwriter.Skin = htmlSkin;
                subwriter.Current_Aggregation = hierarchyObject;
            }
        }
        /// <summary> Writes the search or browse information in JSON format directly to the output stream  </summary>
        /// <param name="Output"> Stream to which to write the JSON search or browse information </param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        protected internal void display_search_results(TextWriter Output, Item_Lookup_Object All_Items_Lookup)
        {
            // If results are null, or no results, return empty string
            if ((paged_results == null) || (results_statistics == null) || (results_statistics.Total_Items <= 0))
                return;

            Output.Write("[");

            // Step through all the results
            int i = 1;
            foreach (iSearch_Title_Result titleResult in paged_results)
            {
                // Always get the first item for things like the main link and thumbnail
                iSearch_Item_Result firstItemResult = titleResult.Get_Item(0);

                // Determine a thumbnail
                string thumb = currentGreenstoneImageRoot + titleResult.BibID.Substring(0,2) + "/" + titleResult.BibID.Substring(2,2) + "/" + titleResult.BibID.Substring(4,2) + "/" + titleResult.BibID.Substring(6,2) + "/" + titleResult.BibID.Substring(8) + "/" + firstItemResult.VID + "/" + firstItemResult.MainThumbnail;
                if ((thumb.ToUpper().IndexOf(".JPG") < 0) && (thumb.ToUpper().IndexOf(".GIF") < 0))
                {
                    thumb = currentMode.Default_Images_URL + "NoThumb.jpg";
                }
                thumb = thumb.Replace("\\", "/").Replace("//", "/").Replace("http:/", "http://");

                // Was a previous item/title included here?
                if (i > 1)
                    Output.Write(",");
                Output.Write("{\"collection_item\":{\"name\":\"" + firstItemResult.Title.Trim().Replace("\"", "'") + "\",\"url\":\"" + SobekCM_Library_Settings.System_Base_URL + titleResult.BibID + "/" + firstItemResult.VID + "\",\"collection_code\":\"\",\"id\":\"" + titleResult.BibID + "_" + firstItemResult.VID + "\",\"thumb_url\":\"" + thumb + "\"}}");

                i++;
            }

            Output.Write("]");
        }
        private void Delete_Item(User_Object User, Item_Lookup_Object All_Items_Lookup, Custom_Tracer Tracer)
        {
            errorCode = 0;

            // Get the current item details
            string vid_location = item.Source_Directory;
            string bib_location = (new DirectoryInfo(vid_location)).Parent.FullName;
            //if (errorCode == -1)
            //{
            //	// Get item details
            //	DataSet itemDetails = SobekCM_Database.Get_Item_Details(currentMode.BibID, currentMode.VID, Tracer);

            //	// If the itemdetails was null, this item is somehow invalid item then
            //	if (itemDetails == null)
            //	{
            //		Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Item indicated is not valid", Custom_Trace_Type_Enum.Error);
            //		errorCode = 2;
            //	}
            //	else
            //	{
            //		// Get the location for this METS file from the returned value
            //		DataRow mainItemRow = itemDetails.Tables[2].Rows[0];
            //		bib_location = SobekCM_Library_Settings.Image_Server_Network + mainItemRow["File_Location"].ToString().Replace("/", "\\");
            //		vid_location = bib_location + "\\" + currentMode.VID;
            //	}
            //}

            // Perform the database delete
            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Perform database update");
            bool database_result2 = SobekCM_Database.Delete_SobekCM_Item(currentMode.BibID, currentMode.VID, User.Is_System_Admin, String.Empty);

            // Perform the SOLR delete
            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Perform solr delete");
            Solr.Solr_Controller.Delete_Resource_From_Index(SobekCM_Library_Settings.Document_Solr_Index_URL, SobekCM_Library_Settings.Page_Solr_Index_URL, currentMode.BibID, currentMode.VID);

            if (!database_result2)
            {
                Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Error performing delete in the database", Custom_Trace_Type_Enum.Error);
                errorCode = 3;
            }
            else
            {
                // Move the folder to deletes
                try
                {
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Move resource files to RECYCLE BIN folder");

                    // Make sure upper RECYCLE BIN folder exists, or create it
                    string delete_folder = SobekCM_Library_Settings.Image_Server_Network + "RECYCLE BIN";
                    if (!Directory.Exists(delete_folder))
                        Directory.CreateDirectory(delete_folder);

                    // Create the bib level folder next
                    string bib_folder = SobekCM_Library_Settings.Image_Server_Network + "RECYCLE BIN\\" + currentMode.BibID;
                    if (!Directory.Exists(bib_folder))
                        Directory.CreateDirectory(bib_folder);

                    // Ensure the VID folder does not exist
                    string vid_folder = SobekCM_Library_Settings.Image_Server_Network + "RECYCLE BIN\\" + currentMode.BibID + "\\" + currentMode.VID;
                    if (Directory.Exists(vid_folder))
                        Directory.Move(vid_folder, vid_folder + "_OLD");

                    // Move the VID folder over now
                    Directory.Move(vid_location, vid_folder);

                    // Check if this was the last VID under this BIB
                    if (Directory.GetDirectories(bib_location).Length == 0)
                    {
                        // Move all files over to the bib folder then
                        string[] bib_files = Directory.GetFiles(bib_location);
                        foreach (string thisFile in bib_files)
                        {
                            string fileName = (new FileInfo(thisFile)).Name;
                            string new_file = bib_folder + "\\" + fileName;
                            File.Move(thisFile, new_file);
                        }
                    }
                }
                catch (Exception ee)
                {
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Error moving the folder and files to the RECYCLE BIN folder", Custom_Trace_Type_Enum.Error);
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", ee.Message, Custom_Trace_Type_Enum.Error);
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", ee.StackTrace, Custom_Trace_Type_Enum.Error);
                    errorCode = 4;
                }

                // Remove from the item list
                All_Items_Lookup.Remove_Item(currentMode.BibID, currentMode.VID);

                // Also remove from the cache
                Cached_Data_Manager.Remove_Digital_Resource_Object(currentMode.BibID, currentMode.VID, Tracer);
            }
        }
 /// <summary> Constructor for a new instance of the Full_ResultsViewer class </summary>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 public Full_ResultsViewer(Item_Lookup_Object All_Items_Lookup)
 {
     base.All_Items_Lookup = All_Items_Lookup;
 }
        /// <summary> Parse the query and set the internal variables </summary>
        /// <param name="QueryString"> QueryString collection passed from the main page </param>
        /// <param name="Navigator"> Navigation object to hold the mode information </param>
        /// <param name="Base_URL">Requested base URL (without query string, etc..)</param>
        /// <param name="User_Languages"> Languages preferred by user, per their browser settings </param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections </param>
        /// <param name="Aggregation_Aliases"> List of all existing aliases for existing aggregations</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library</param>
        /// <param name="URL_Portals"> List of all web portals into this system </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        public void Parse_Query(NameValueCollection QueryString,
            SobekCM_Navigation_Object Navigator,
            string Base_URL,
            string[] User_Languages,
            Aggregation_Code_Manager Code_Manager,
            Dictionary<string, string> Aggregation_Aliases,
            ref Item_Lookup_Object All_Items_Lookup,
            Portal_List URL_Portals,
            Custom_Tracer Tracer )
        {
            // This is the legacy URL reader, so this is not optimized as well as the new one.
            // Just make sure the item list is loaded here
            SobekCM_Database.Verify_Item_Lookup_Object(true, ref All_Items_Lookup, Tracer);

            // Set default mode to error
            Navigator.Mode = Display_Mode_Enum.Error;

            // If this has 'verb' then this is an OAI-PMH request
            if ( QueryString["verb"] != null )
            {
                Navigator.Writer_Type = Writer_Type_Enum.OAI;
                return;
            }

            // Is there a TOC state set?
            if (QueryString["toc"] != null)
            {
                if (QueryString["toc"] == "y")
                {
                    Navigator.TOC_Display = TOC_Display_Type_Enum.Show;
                }
                else if ( QueryString["toc"] == "n" )
                {
                    Navigator.TOC_Display = TOC_Display_Type_Enum.Hide;
                }
            }

            // Is there a language defined?  If so, load right into the navigator
            if ( QueryString["l"] != null )
            {
                if (( QueryString["l"].ToUpper() == "ES" ) || ( QueryString["l"].ToUpper() == "SP" ))
                {
                    Navigator.Language = Web_Language_Enum.Spanish;
                }
                if ( QueryString["l"].ToUpper() == "FR" )
                {
                    Navigator.Language = Web_Language_Enum.French;
                }
            }

            // If there is flag indicating to show the trace route, save it
            if (QueryString["trace"] != null)
            {
                Navigator.Trace_Flag = QueryString["trace"].ToUpper() == "NO" ? Trace_Flag_Type_Enum.No : Trace_Flag_Type_Enum.Explicit;
            }
            else
            {
                Navigator.Trace_Flag = Trace_Flag_Type_Enum.Unspecified;
            }

            // Collect all the values into the strings
            Collect_Strings( QueryString );

            // Get the valid URL Portal
            Navigator.Default_Aggregation = "all";
            Portal urlPortal = URL_Portals.Get_Valid_Portal(Base_URL);
            Navigator.SobekCM_Instance_Abbreviation = urlPortal.Abbreviation;
            if (urlPortal.Default_Aggregation.Length > 0)
            {
                Navigator.Default_Aggregation = urlPortal.Default_Aggregation;
                Navigator.Aggregation = urlPortal.Default_Aggregation;
            }
            if (urlPortal.Default_Web_Skin.Length > 0)
            {
                Navigator.Default_Skin = urlPortal.Default_Web_Skin;
                Navigator.Skin = urlPortal.Default_Web_Skin;
                Navigator.Skin_In_URL = false;
            }

            // Save the interface
            if (currSkin.Length > 0)
            {
                Navigator.Skin = currSkin.ToLower();
                Navigator.Skin_In_URL = true;
            }

            // Get the return url if there was one
            if (return_url.Length > 0)
            {
                Navigator.Return_URL = HttpUtility.UrlDecode(return_url);
            }

            // If there are no values in the query string, the
            // current mode should be the default
            if (( QueryString.Keys.Count == 0 ) && ( aggregation.Length == 0 ))
            {
                Navigator.Mode = Display_Mode_Enum.Aggregation;
                Navigator.Aggregation_Type = Aggregation_Type_Enum.Home;
                Navigator.Home_Type = Home_Type_Enum.List;
                return;
            }

            char default_html = 'h';
            if (HttpContext.Current != null)
            {
                if ((HttpContext.Current.Session["user"] != null) || (HttpContext.Current.Request.Cookies["UfdcUser"] != null))
                    default_html = 'l';
            }

            // If there is no mode listed, just set it to 'h' for home
            if (string.IsNullOrEmpty(mode))
            {
                if ( search.Length > 0 )
                {
                    mode = default_html + "sb";
                }
                else
                {
                    if (( item.Length > 0 ) || ( bibid.Length > 0 ))
                    {
                        mode = default_html + "d";
                    }
                    else
                    {
                        mode = default_html + "hl";
                    }
                }
            }

            // If the length is insufficient, try adding 'h' in front
            if ( mode.Length == 1 )
                mode = default_html + mode;

            // Check for writer mode
            switch( mode[0] )
            {
                case 'x':
                    Navigator.Writer_Type = Writer_Type_Enum.XML;
                    break;

                case 'd':
                    Navigator.Writer_Type = Writer_Type_Enum.DataSet;
                    break;

                case 't':
                    Navigator.Writer_Type = Writer_Type_Enum.Text;
                    break;

                case 'j':
                    Navigator.Writer_Type = Writer_Type_Enum.JSON;
                    break;

                case 'l':
                    Navigator.Writer_Type = Writer_Type_Enum.HTML_LoggedIn;
                    break;

                default:
                    Navigator.Writer_Type = Writer_Type_Enum.HTML;
                    break;
            }

            // Save the aggregation information
            Navigator.Aggregation = aggregation;
            Navigator.SubAggregation = subaggregation;

            // Perform switch, based on the mode
            switch ( mode[1] )
            {
                case 'a':
                    Admin_Block(Navigator);
                    return;

                case 'b':
                    Navigator.Mode = Display_Mode_Enum.Aggregation;
                    Navigator.Aggregation_Type = Aggregation_Type_Enum.Browse_Info;
                    Browse_Info_Block( Navigator );
                    return;

                case 'c':
                    if ((mode == "hcs") || ( mode == "lcs" ))
                    {
                        Navigator.Mode = Display_Mode_Enum.Contact_Sent;
                    }
                    else
                    {
                        Navigator.Mode = Display_Mode_Enum.Contact;
                        Navigator.Error_Message = error_message;
                    }
                    Navigator.Aggregation = aggregation;
                    return;

                case 'd':
                    Item_Display_Block(Navigator);
                    return;

                case 'e':
                    Text_Display(Navigator);
                    return;

                case 'f':
                    Item_Print_Block(Navigator);
                    return;

                case 'g':
                    Public_Folder_Block(Navigator);
                    break;

                case 'h':
                    Home_Block( Navigator );
                    return;

                case 'i':
                    Navigator.Mode = Display_Mode_Enum.Aggregation;
                    Navigator.Aggregation_Type = Aggregation_Type_Enum.Browse_Info;
                    Browse_Info_Block(Navigator);
                    return;

                case 'm':
                    My_Sobek_Block(Navigator);
                    return;

                case 'p':
                    Navigator.Mode = Display_Mode_Enum.Preferences;
                    return;

                case 'r':
                    Results_Block(Navigator);
                    return;

                case 's':    // Performing a basic search
                    Search_Block( Navigator );
                    return;

                case 't':
                    Statistics_Block(Navigator);
                    return;

                case 'z':
                    Navigator.Mode = Display_Mode_Enum.Reset;
                    return;

                default:
                    Navigator.Mode = Display_Mode_Enum.Error;
                    Navigator.Error_Message = "Unknown mode '" + mode + "'";
                    return;
            }
        }
        /// <summary> Constructor for a new instance of the Admin_HtmlSubwriter class </summary>
        /// <param name="Results_Statistics"> Information about the entire set of results for a browse of a user's bookshelf folder </param>
        /// <param name="Paged_Results"> Single page of results for a browse of a user's bookshelf folder, within the entire set </param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Hierarchy_Object"> Current item aggregation object to display </param>
        /// <param name="HTML_Skin"> HTML Web skin which controls the overall appearance of this digital library </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="Current_Item">Current item to edit, if the user is requesting to edit an item</param>
        /// <param name="Aggregation_Aliases"> List of all existing aliases for existing aggregations </param>
        /// <param name="Web_Skin_Collection"> Collection of all the web skins </param>
        /// <param name="Current_User"> Currently logged on user </param>
        /// <param name="Icon_Table"> Dictionary of all the wordmark/icons which can be tagged to the items </param>
        /// <param name="IP_Restrictions"> List of all IP Restriction ranges in use by this digital library </param>
        /// <param name="URL_Portals"> List of all web portals into this system </param>
        /// <param name="Stats_Date_Range"> Object contains the start and end dates for the statistical data in the database </param>
        /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the home page are organized </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        public Admin_HtmlSubwriter(Search_Results_Statistics Results_Statistics,
                                     List<iSearch_Title_Result> Paged_Results,
                                     Aggregation_Code_Manager Code_Manager,
                                     Item_Lookup_Object All_Items_Lookup,
                                     Item_Aggregation Hierarchy_Object,
                                     SobekCM_Skin_Object HTML_Skin,
                                     Language_Support_Info Translator,
                                     SobekCM_Navigation_Object Current_Mode,
                                     SobekCM_Item Current_Item,
                                     Dictionary<string,string> Aggregation_Aliases,
                                     SobekCM_Skin_Collection Web_Skin_Collection,
                                     User_Object Current_User,
                                     IP_Restriction_Ranges IP_Restrictions,
                                     Dictionary<string, Wordmark_Icon> Icon_Table,
                                     Portal_List URL_Portals,
                                     Statistics_Dates Stats_Date_Range,
                                     List<Thematic_Heading> Thematic_Headings,
                                     Custom_Tracer Tracer )
        {
            Tracer.Add_Trace("Admin_HtmlSubwriter.Constructor", "Saving values and geting user object back from the session");

            resultsStatistics = Results_Statistics;
            pagedResults = Paged_Results;
            codeManager = Code_Manager;
            itemList = All_Items_Lookup;
            htmlSkin = HTML_Skin;
            translator = Translator;
            currentCollection = Hierarchy_Object;
            currentItem = Current_Item;
            user = Current_User;
            ipRestrictions = IP_Restrictions;
            iconTable = Icon_Table;
            statsDates = Stats_Date_Range;

            if (Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Log_Out)
            {
                Tracer.Add_Trace("Admin_HtmlSubwriter.Constructor", "Performing logout");

                HttpContext.Current.Session["user"] = null;
                HttpContext.Current.Response.Redirect("?");
            }

            if ((Current_Mode.My_Sobek_Type != My_Sobek_Type_Enum.Logon) && (user != null) && (user.Is_Temporary_Password))
            {
                Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.New_Password;
            }

            if (Current_Mode.Logon_Required)
                Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Logon;

            // If the user is not an admin, and admin was selected, reroute this
            if ((!Current_User.Is_System_Admin) && (!Current_User.Is_Portal_Admin))
            {
                Current_Mode.Mode = Display_Mode_Enum.My_Sobek;
                Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                Current_Mode.My_Sobek_SubMode = String.Empty;
                HttpContext.Current.Response.Redirect(Current_Mode.Redirect_URL());
            }

            Tracer.Add_Trace("Admin_HtmlSubwriter.Constructor", "Building the my sobek viewer object");
            switch (Current_Mode.Admin_Type)
            {
                case Admin_Type_Enum.Aggregation_Single:
                    adminViewer = new Aggregation_Single_AdminViewer(user, Current_Mode, codeManager, Thematic_Headings, Web_Skin_Collection, Tracer);
                    break;

                case Admin_Type_Enum.Home:
                    adminViewer = new Home_AdminViewer(user, Current_Mode, Tracer);
                    break;

                case Admin_Type_Enum.Builder_Status:
                    adminViewer = new Builder_AdminViewer(user, Current_Mode);
                    break;

                case Admin_Type_Enum.Interfaces:
                    adminViewer = new Skins_AdminViewer(user, Current_Mode, Web_Skin_Collection, Tracer);
                    break;

                case Admin_Type_Enum.Forwarding:
                    adminViewer = new Aliases_AdminViewer(user, Current_Mode, Aggregation_Aliases, Tracer);
                    break;

                case Admin_Type_Enum.Wordmarks:
                    adminViewer = new Wordmarks_AdminViewer(user, Current_Mode, Tracer);
                    break;

                case Admin_Type_Enum.URL_Portals:
                    adminViewer = new Portals_AdminViewer(user, Current_Mode, URL_Portals, Tracer);
                    break;

                case Admin_Type_Enum.Users:
                    adminViewer = new Users_AdminViewer(user, Current_Mode, codeManager, Tracer);
                    break;

                case Admin_Type_Enum.User_Groups:
                    adminViewer = new User_Group_AdminViewer(user, Current_Mode, codeManager, Tracer);
                    break;

                case Admin_Type_Enum.Aggregations_Mgmt:
                    adminViewer = new Aggregations_Mgmt_AdminViewer(user, Current_Mode, codeManager, Tracer);
                    break;

                case Admin_Type_Enum.IP_Restrictions:
                    adminViewer = new IP_Restrictions_AdminViewer(user, Current_Mode, ipRestrictions, Tracer);
                    break;

                case Admin_Type_Enum.Thematic_Headings:
                    adminViewer = new Thematic_Headings_AdminViewer(user, Current_Mode, Thematic_Headings, Tracer);
                    break;

                case Admin_Type_Enum.Settings:
                    adminViewer = new Settings_AdminViewer(user, Current_Mode, Tracer);
                    break;

                case Admin_Type_Enum.Projects:
                    if (Current_Mode.My_Sobek_SubMode.Length > 1)
                    {
                        string project_code = Current_Mode.My_Sobek_SubMode.Substring(1);
                        Tracer.Add_Trace("MySobek_HtmlSubwriter.Constructor", "Checking cache for valid project file");
                        if (user != null)
                        {
                            SobekCM_Item projectObject = Cached_Data_Manager.Retrieve_Project(user.UserID, project_code, Tracer);
                            if (projectObject != null)
                            {
                                Tracer.Add_Trace("MySobek_HtmlSubwriter.Constructor", "Valid project file found in cache");
                                adminViewer = new Edit_Item_Metadata_MySobekViewer(user, Current_Mode, itemList, projectObject, codeManager, iconTable, htmlSkin, Tracer);
                            }
                            else
                            {
                                if (SobekCM_Database.Get_All_Projects_Templates(Tracer).Tables[0].Select("ProjectCode='" + project_code + "'").Length > 0)
                                {
                                    Tracer.Add_Trace("MySobek_HtmlSubwriter.Constructor", "Building project file from (possible) PMETS");
                                    string pmets_file = SobekCM_Library_Settings.Base_MySobek_Directory + "projects\\" + Current_Mode.My_Sobek_SubMode.Substring(1) + ".pmets";
                                    SobekCM_Item pmets_item = File.Exists(pmets_file) ? SobekCM_Item.Read_METS(pmets_file) : new SobekCM_Item();
                                    pmets_item.Bib_Info.Main_Title.Title = "Project level metadata for '" + project_code + "'";
                                    pmets_item.Bib_Info.SobekCM_Type = TypeOfResource_SobekCM_Enum.Project;
                                    pmets_item.BibID = project_code.ToUpper();
                                    pmets_item.VID = "00001";
                                    pmets_item.Source_Directory = SobekCM_Library_Settings.Base_MySobek_Directory +  "projects\\";

                                    Tracer.Add_Trace("MySobek_HtmlSubwriter.Constructor", "Adding project file to cache");

                                    Cached_Data_Manager.Store_Project(user.UserID, project_code, pmets_item, Tracer);

                                    adminViewer = new Edit_Item_Metadata_MySobekViewer(user, Current_Mode, itemList, pmets_item, codeManager, iconTable, htmlSkin, Tracer);
                                }
                            }
                        }
                    }

                    if (adminViewer == null)
                        adminViewer = new Projects_AdminViewer(user, Current_Mode, Tracer);
                    break;
            }

            // Pass in the navigation and translator information
            adminViewer.CurrentMode = Current_Mode;
            adminViewer.Translator = translator;
        }
 /// <summary> Constructor for a new instance of the Export_File_ResultsViewer class </summary>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 /// <param name="Current_User"> Current user object </param>
 public Export_File_ResultsViewer(Item_Lookup_Object All_Items_Lookup, User_Object Current_User)
 {
     base.All_Items_Lookup = All_Items_Lookup;
     currentUser = Current_User;
     Results_Per_Page = 1000;
 }
        /// <summary> Constructor for a new instance of the SobekCM_Navigation_Object which stores 
        /// all of the information about an individual request. </summary>
        /// <param name="QueryString">Query string information for analysis</param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections </param>
        /// <param name="Aggregation_Aliases"> List of all existing aliases for existing aggregations</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library</param>
        /// <param name="URL_Portals"> List of all web portals into this system </param>
        public SobekCM_Navigation_Object(NameValueCollection QueryString, Aggregation_Code_Manager Code_Manager, Dictionary<string, string> Aggregation_Aliases, ref Item_Lookup_Object All_Items_Lookup, Portal_List URL_Portals)
        {
            // Do general item construction
            Constructor_Helper();

            // Analyze the query string with the default analyzer
            SobekCM_QueryString_Analyzer analyzer = new SobekCM_QueryString_Analyzer();
            analyzer.Parse_Query(QueryString, this, String.Empty, null, Code_Manager, Aggregation_Aliases, ref All_Items_Lookup, URL_Portals, null);
        }
        /// <summary> Constructor for a new instance of the SobekCM_Navigation_Object which stores 
        /// all of the information about an individual request. </summary>
        /// <param name="QueryString">Query string information for analysis</param>
        /// <param name="Base_URL"> Requested base URL (without query string, etc..)</param>
        /// <param name="User_Languages"> Languages preferred by user, per their browser settings </param>
        /// <param name="Analyzer">Object to user for the URL analysis</param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections </param>
        /// <param name="Aggregation_Aliases"> List of all existing aliases for existing aggregations</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library</param>
        /// <param name="URL_Portals"> List of all web portals into this system </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        public SobekCM_Navigation_Object(NameValueCollection QueryString, string Base_URL, string[] User_Languages, iSobekCM_QueryString_Analyzer Analyzer, Aggregation_Code_Manager Code_Manager, Dictionary<string, string> Aggregation_Aliases, ref Item_Lookup_Object All_Items_Lookup, Portal_List URL_Portals, Custom_Tracer Tracer )
        {
            // Do general item construction
            Constructor_Helper();

            // Analyze the query string with the provided analyzer
            Analyzer.Parse_Query(QueryString, this, Base_URL, User_Languages, Code_Manager, Aggregation_Aliases, ref All_Items_Lookup, URL_Portals, Tracer);
        }
 /// <summary> Constructor for a new instance of the Full_ResultsViewer class </summary>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 public Google_Map_ResultsViewer(Item_Lookup_Object All_Items_Lookup)
 {
     base.All_Items_Lookup = All_Items_Lookup;
 }
        /// <summary> Constructor creates a new instance of the Aggregation_HtmlSubwriter class </summary>
        /// <param name="Hierarchy_Object"> Current item aggregation object to display </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="HTML_Skin"> HTML Web skin which controls the overall appearance of this digital library </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        /// <param name="Browse_Object"> Object contains all the basic information about any browse or info display </param>
        /// <param name="Paged_Results"> Paged results to display within a browse or search result </param>
        /// <param name="Results_Statistics"> Information about the entire set of results for a search or browse </param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the home page are organized </param>
        /// <param name="Current_User"> Currently logged on user </param>
        /// <param name="IP_Restrictions"> IP restrictions, used to determine if a user has access to a particular item </param>
        /// <param name="Static_Web_Content"> HTML content-based browse, info, or imple CMS-style web content objects.  These are objects which are read from a static HTML file and much of the head information must be maintained </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        public Aggregation_HtmlSubwriter(Item_Aggregation Hierarchy_Object, 
            SobekCM_Navigation_Object Current_Mode, SobekCM_Skin_Object HTML_Skin, 
            Language_Support_Info Translator, 
            Item_Aggregation_Browse_Info Browse_Object,
            Search_Results_Statistics Results_Statistics,
            List<iSearch_Title_Result> Paged_Results,
            Aggregation_Code_Manager Code_Manager, Item_Lookup_Object All_Items_Lookup,
            List<Thematic_Heading> Thematic_Headings, User_Object Current_User,
            IP_Restriction_Ranges IP_Restrictions,
            HTML_Based_Content Static_Web_Content,
            Custom_Tracer Tracer )
        {
            currentUser = Current_User;
            base.Hierarchy_Object = Hierarchy_Object;
            currentMode = Current_Mode;
            Skin = HTML_Skin;
            translator = Translator;
            thisBrowseObject = Browse_Object;
            thisStaticBrowseObject = Static_Web_Content;
            codeManager = Code_Manager;
            itemList = All_Items_Lookup;
            thematicHeadings = Thematic_Headings;
            ipRestrictions = IP_Restrictions;
            resultsStatistics = Results_Statistics;
            pagedResults = Paged_Results;

            NameValueCollection form = HttpContext.Current.Request.Form;
            if (form["item_action"] != null)
            {
                string action = form["item_action"].ToLower().Trim();

                if (action == "add_aggregation")
                {
                    SobekCM_Database.User_Set_Aggregation_Home_Page_Flag(currentUser.UserID, base.Hierarchy_Object.Aggregation_ID, true, Tracer);
                    currentUser.Set_Aggregation_Home_Page_Flag(base.Hierarchy_Object.Code, base.Hierarchy_Object.Name, true);
                    HttpContext.Current.Session.Add("ON_LOAD_MESSAGE", "Added aggregation to your home page");
                }

                if (action == "remove_aggregation")
                {
                    int removeAggregationID = base.Hierarchy_Object.Aggregation_ID;
                    string remove_code = base.Hierarchy_Object.Code;
                    string remove_name = base.Hierarchy_Object.Name;

                    if ((form["aggregation"] != null) && (form["aggregation"].Length > 0))
                    {
                        Item_Aggregation_Related_Aggregations aggrInfo = codeManager[form["aggregation"]];
                        if (aggrInfo != null)
                        {
                            remove_code = aggrInfo.Code;
                            removeAggregationID = aggrInfo.ID;
                        }
                    }

                    SobekCM_Database.User_Set_Aggregation_Home_Page_Flag(currentUser.UserID, removeAggregationID, false, Tracer);
                    currentUser.Set_Aggregation_Home_Page_Flag(remove_code, remove_name, false);

                    if (currentMode.Home_Type != Home_Type_Enum.Personalized)
                    {
                        HttpContext.Current.Session.Add("ON_LOAD_MESSAGE", "Removed aggregation from your home page");
                    }
                }

                if (action == "private_folder")
                {
                    User_Folder thisFolder = currentUser.Get_Folder(form["aggregation"]);
                    if (SobekCM_Database.Edit_User_Folder(thisFolder.Folder_ID, currentUser.UserID, -1, thisFolder.Folder_Name, false, String.Empty, Tracer) >= 0)
                        thisFolder.isPublic = false;
                }

                if (action == "email")
                {
                    string address = form["email_address"].Replace(";", ",").Trim();
                    string comments = form["email_comments"].Trim();
                    string format = form["email_format"].Trim().ToUpper();

                    if (address.Length > 0)
                    {
                        // Determine the email format
                        bool is_html_format = true;
                        if (format == "TEXT")
                            is_html_format = false;

                        // CC: the user, unless they are already on the list
                        string cc_list = currentUser.Email;
                        if (address.ToUpper().IndexOf(currentUser.Email.ToUpper()) >= 0)
                            cc_list = String.Empty;

                        // Send the email
                        string any_error = URL_Email_Helper.Send_Email(address, cc_list, comments, currentUser.Full_Name, currentMode.SobekCM_Instance_Abbreviation, is_html_format, HttpContext.Current.Items["Original_URL"].ToString(), base.Hierarchy_Object.Name, "home");
                        HttpContext.Current.Session.Add("ON_LOAD_MESSAGE", any_error.Length > 0 ? any_error : "Your email has been sent");

                        currentMode.isPostBack = true;

                        // Do this to force a return trip (cirumnavigate cacheing)
                        string original_url = HttpContext.Current.Items["Original_URL"].ToString();
                        if (original_url.IndexOf("?") < 0)
                            HttpContext.Current.Response.Redirect(original_url + "?p=" + DateTime.Now.Millisecond, false);
                        else
                            HttpContext.Current.Response.Redirect(original_url + "&p=" + DateTime.Now.Millisecond, false);
                    }
                }
            }

            // If this is a search, verify it is a valid search type
            if (currentMode.Mode == Display_Mode_Enum.Search)
            {
                // Not every collection has every search type...
                ReadOnlyCollection<Search_Type_Enum> possibleSearches = base.Hierarchy_Object.Search_Types;
                if (!possibleSearches.Contains(currentMode.Search_Type))
                {
                    bool found_valid = false;

                    if ((currentMode.Search_Type == Search_Type_Enum.Full_Text) && (possibleSearches.Contains(Search_Type_Enum.dLOC_Full_Text)))
                    {
                        found_valid = true;
                        currentMode.Search_Type = Search_Type_Enum.dLOC_Full_Text;
                    }

                    if ((!found_valid) && (currentMode.Search_Type == Search_Type_Enum.Basic) && (possibleSearches.Contains(Search_Type_Enum.Newspaper)))
                    {
                        found_valid = true;
                        currentMode.Search_Type = Search_Type_Enum.Newspaper;
                    }

                    if (( !found_valid ) && ( possibleSearches.Count > 0 ))
                    {
                        found_valid = true;
                        currentMode.Search_Type = possibleSearches[0];
                    }

                    if ( !found_valid )
                    {
                        currentMode.Mode = Display_Mode_Enum.Aggregation_Home;
                    }
                }
            }

            if (currentMode.Mode == Display_Mode_Enum.Search)
            {
                collectionViewer = AggregationViewer_Factory.Get_Viewer(currentMode.Search_Type, base.Hierarchy_Object, currentMode, currentUser);
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Home)
            {
                collectionViewer = AggregationViewer_Factory.Get_Viewer(base.Hierarchy_Object.Views_And_Searches[0], base.Hierarchy_Object, currentMode);
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Browse_Info)
            {
                if ( resultsStatistics == null )
                {
                    collectionViewer = new Static_Browse_Info_AggregationViewer(thisBrowseObject, thisStaticBrowseObject);
                }
                else
                {
                    collectionViewer = new DataSet_Browse_Info_AggregationViewer(thisBrowseObject, resultsStatistics, pagedResults, codeManager, itemList, currentUser );
                }
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Browse_By)
            {
                collectionViewer = new Metadata_Browse_AggregationViewer( Current_Mode, Hierarchy_Object, Tracer );
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Browse_Map)
            {
                collectionViewer = new Map_Browse_AggregationViewer(Current_Mode, Hierarchy_Object, Tracer);
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Item_Count)
            {
                collectionViewer = new Item_Count_AggregationViewer(Current_Mode, Hierarchy_Object);
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Usage_Statistics)
            {
                collectionViewer = new Usage_Statistics_AggregationViewer(Current_Mode, Hierarchy_Object);
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Private_Items)
            {
                collectionViewer = new Private_Items_AggregationViewer(Current_Mode, Hierarchy_Object, Tracer);
            }

            if (currentMode.Mode == Display_Mode_Enum.Aggregation_Admin_View)
            {
                collectionViewer = new Admin_AggregationViewer(Hierarchy_Object);
            }

            if (collectionViewer != null)
            {
                collectionViewer.Translator = translator;
                collectionViewer.HTML_Skin = HTML_Skin;
                collectionViewer.CurrentMode = Current_Mode;
                collectionViewer.CurrentObject = Hierarchy_Object;
                collectionViewer.Current_User = Current_User;

                // Pull the standard values
                switch (collectionViewer.Selection_Panel_Display)
                {
                    case Selection_Panel_Display_Enum.Selectable:
                        if (form["show_subaggrs"] != null)
                        {
                            string show_subaggrs = form["show_subaggrs"].ToUpper();
                            if (show_subaggrs == "TRUE")
                                currentMode.Show_Selection_Panel = true;
                        }
                        break;

                    case Selection_Panel_Display_Enum.Always:
                        currentMode.Show_Selection_Panel = true;
                        break;
                }
            }
        }
        private void Perform_Database_Search(Custom_Tracer Tracer, List<string> Terms, List<string> Web_Fields, int ActualCount, SobekCM_Navigation_Object Current_Mode, int Current_Sort, Item_Aggregation Aggregation_Object, Item_Lookup_Object All_Items_Lookup, int Results_Per_Page, bool Potentially_Include_Facets, out Search_Results_Statistics Complete_Result_Set_Info, out List<List<iSearch_Title_Result>> Paged_Results, bool Need_Search_Statistics)
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("SobekCM_Assistant.Perform_Database_Sear`ch", "Query the database for search results");
            }

            // Get the list of facets first
            List<short> facetsList = Aggregation_Object.Facets;
            if (!Potentially_Include_Facets)
                facetsList.Clear();

            // Set the return values to NULL initially
            Complete_Result_Set_Info = null;

            const bool includePrivate = false;

            // Special code for searching by bibid, oclc, or aleph
            if (ActualCount == 1)
            {
                // Is this a BIBID search?
                if ((Web_Fields[0] == "BI") && ( Terms[0].IndexOf("*") < 0 ) && ( Terms[0].Length >= 10 ))
                {
                    string bibid = Terms[0].ToUpper();
                    string vid = String.Empty;
                    if (bibid.Length > 10)
                    {
                        if ((bibid.IndexOf("_") == 10) && ( bibid.Length > 11 ))
                        {
                            vid = bibid.Substring(11).PadLeft(5, '0');
                            bibid = bibid.Substring(0, 10);
                        }
                        else if ((bibid.IndexOf(":") == 10) && ( bibid.Length > 11 ))
                        {
                            vid = bibid.Substring(11).PadLeft(5, '0');
                            bibid = bibid.Substring(0, 10);
                        }
                        else if (bibid.Length == 15)
                        {
                            vid = bibid.Substring(10);
                            bibid = bibid.Substring(0, 10);
                        }
                    }

                    if (bibid.Length == 10)
                    {
                        if (vid.Length == 5)
                        {
                            if (All_Items_Lookup.Contains_BibID_VID(bibid, vid))
                            {
                                string redirect_url = Current_Mode.Base_URL + bibid + "/" + vid;
                                if ( Current_Mode.Writer_Type == Writer_Type_Enum.HTML_LoggedIn )
                                    redirect_url = Current_Mode.Base_URL + "l/" + bibid + "/" + vid;
                                HttpContext.Current.Response.Redirect(redirect_url);
                            }
                        }
                        else
                        {
                            if (All_Items_Lookup.Contains_BibID(bibid))
                            {
                                string redirect_url = Current_Mode.Base_URL + bibid;
                                if (Current_Mode.Writer_Type == Writer_Type_Enum.HTML_LoggedIn)
                                    redirect_url = Current_Mode.Base_URL + "l/" + bibid;
                                HttpContext.Current.Response.Redirect(redirect_url);
                            }
                        }
                    }
                }

                // Was this a OCLC search?
                if ((Web_Fields[0] == "OC") && (Terms[0].Length > 0))
                {
                    bool is_number = Terms[0].All(Char.IsNumber);

                    if (is_number)
                    {
                        long oclc = Convert.ToInt64(Terms[0]);
                        Multiple_Paged_Results_Args returnArgs = SobekCM_Database.Items_By_OCLC_Number(oclc, false, Results_Per_Page, Current_Sort, Need_Search_Statistics, Tracer);
                        if (Need_Search_Statistics)
                            Complete_Result_Set_Info = returnArgs.Statistics;
                        Paged_Results = returnArgs.Paged_Results;
                        return;
                    }
                }

                // Was this a ALEPH search?
                if ((Web_Fields[0] == "AL") && (Terms[0].Length > 0))
                {
                    bool is_number = Terms[0].All(Char.IsNumber);

                    if (is_number)
                    {
                        int aleph = Convert.ToInt32(Terms[0]);
                        Multiple_Paged_Results_Args returnArgs = SobekCM_Database.Items_By_ALEPH_Number(aleph, false, Results_Per_Page, Current_Sort, Need_Search_Statistics, Tracer);
                        if (Need_Search_Statistics)
                            Complete_Result_Set_Info = returnArgs.Statistics;
                        Paged_Results = returnArgs.Paged_Results;
                        return;
                    }
                }
            }

            List<short> links = new List<short>();
            List<short> db_fields = new List<short>();
            List<string> db_terms = Terms.ToList();

            // Step through all the web fields and convert to db fields
            for (int i = 0; i < ActualCount; i++)
            {
                if (Web_Fields[i].Length > 1)
                {
                    // Find the joiner
                    if ((Web_Fields[i][0] == '+') || (Web_Fields[i][0] == '=') || (Web_Fields[i][0] == '-'))
                    {
                        if (i != 0)
                        {
                            if (Web_Fields[i][0] == '+')
                                links.Add(0);
                            if (Web_Fields[i][0] == '=')
                                links.Add(1);
                            if (Web_Fields[i][0] == '-')
                                links.Add(2);
                        }
                        Web_Fields[i] = Web_Fields[i].Substring(1);
                    }
                    else
                    {
                        if (i != 0)
                        {
                            links.Add(0);
                        }
                    }

                    // Find the db field number
                    db_fields.Add(Metadata_Field_Number(Web_Fields[i]));
                }

                // Also add starting and ending quotes to all the valid searches
                if (db_terms[i].Length > 0)
                {
                    if ((db_terms[i].IndexOf("\"") < 0) && (db_terms[i].IndexOf(" ") < 0))
                    {
                        // Since this is a single word, see what type of special codes to include
                        switch (Current_Mode.Search_Precision)
                        {
                            case Search_Precision_Type_Enum.Contains:
                                db_terms[i] = "\"" + db_terms[i] + "\"";
                                break;

                            case Search_Precision_Type_Enum.Inflectional_Form:
                                // If there are any non-characters, don't use inflectional for this term
                                bool inflectional = db_terms[i].All(Char.IsLetter);
                                if (inflectional)
                                {
                                    db_terms[i] = "FORMSOF(inflectional," + db_terms[i] + ")";
                                }
                                else
                                {
                                    db_terms[i] = "\"" + db_terms[i] + "\"";
                                }
                                break;

                            case Search_Precision_Type_Enum.Synonmic_Form:
                                // If there are any non-characters, don't use thesaurus for this term
                                bool thesaurus = db_terms[i].All(Char.IsLetter);
                                if (thesaurus)
                                {
                                    db_terms[i] = "FORMSOF(thesaurus," + db_terms[i] + ")";
                                }
                                else
                                {
                                    db_terms[i] = "\"" + db_terms[i] + "\"";
                                }
                                break;
                        }
                    }
                    else
                    {
                        if (Current_Mode.Search_Precision != Search_Precision_Type_Enum.Exact_Match)
                        {
                            db_terms[i] = "\"" + db_terms[i] + "\"";
                        }
                    }
                }
            }

            // If this is an exact match, just do the search
            if (Current_Mode.Search_Precision == Search_Precision_Type_Enum.Exact_Match)
            {
                Multiple_Paged_Results_Args returnArgs = SobekCM_Database.Perform_Metadata_Exact_Search_Paged(db_terms[0], db_fields[0], includePrivate, Current_Mode.Aggregation, Results_Per_Page, Current_Mode.Page, Current_Sort, Need_Search_Statistics, facetsList, Need_Search_Statistics, Tracer);
                if (Need_Search_Statistics)
                    Complete_Result_Set_Info = returnArgs.Statistics;
                Paged_Results = returnArgs.Paged_Results;
            }
            else
            {
                // Finish filling up the fields and links
                while (links.Count < 9)
                    links.Add(0);
                while (db_fields.Count < 10)
                    db_fields.Add(-1);
                while (db_terms.Count < 10)
                    db_terms.Add(String.Empty);

                // See if this is a simple search, which can use a more optimized search routine
                bool simplified_search = db_fields.All(field => (field <= 0));

                // Perform either the simpler metadata search, or the more complex
                if (simplified_search)
                {
                    StringBuilder searchBuilder = new StringBuilder();
                    for (int i = 0; i < db_terms.Count; i++)
                    {
                        if (db_terms[i].Length > 0)
                        {
                            if (i > 0)
                            {
                                if (i > links.Count)
                                {
                                    searchBuilder.Append(" AND ");
                                }
                                else
                                {
                                    switch (links[i - 1])
                                    {
                                        case 0:
                                            searchBuilder.Append(" AND ");
                                            break;

                                        case 1:
                                            searchBuilder.Append(" OR ");
                                            break;

                                        case 2:
                                            searchBuilder.Append(" AND NOT ");
                                            break;
                                    }
                                }
                            }

                            searchBuilder.Append(db_terms[i]);
                        }
                    }

                    Multiple_Paged_Results_Args returnArgs = SobekCM_Database.Perform_Metadata_Search_Paged(searchBuilder.ToString(), includePrivate, Current_Mode.Aggregation, Results_Per_Page, Current_Mode.Page, Current_Sort, Need_Search_Statistics, facetsList, Need_Search_Statistics, Tracer);
                    if (Need_Search_Statistics)
                        Complete_Result_Set_Info = returnArgs.Statistics;
                    Paged_Results = returnArgs.Paged_Results;
                }
                else
                {
                    // Perform search in the database
                    Multiple_Paged_Results_Args returnArgs = SobekCM_Database.Perform_Metadata_Search_Paged(db_terms[0], db_fields[0], links[0], db_terms[1], db_fields[1], links[1], db_terms[2], db_fields[2], links[2], db_terms[3],
                                                                                                            db_fields[3], links[3], db_terms[4], db_fields[4], links[4], db_terms[5], db_fields[5], links[5], db_terms[6], db_fields[6], links[6], db_terms[7], db_fields[7], links[7], db_terms[8], db_fields[8],
                                                                                                            links[8], db_terms[9], db_fields[9], includePrivate, Current_Mode.Aggregation, Results_Per_Page, Current_Mode.Page, Current_Sort, Need_Search_Statistics, facetsList, Need_Search_Statistics, Tracer);
                    if (Need_Search_Statistics)
                        Complete_Result_Set_Info = returnArgs.Statistics;
                    Paged_Results = returnArgs.Paged_Results;
                }
            }
        }
        /// <summary> Constructor for a new instance of the Group_Add_Volume_MySobekViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="All_Items_Lookup"> Allows individual items to be retrieved by various methods as <see cref="Single_Item"/> objects.</param>
        /// <param name="Current_Item"> Individual digital resource to be edited by the user </param>
        /// <param name="Code_Manager"> Code manager contains the list of all valid aggregation codes </param>
        /// <param name="HTML_Skin"> HTML Web skin which controls the overall appearance of this digital library </param>
        /// <param name="Icon_Table"> Dictionary of all the wordmark/icons which can be tagged to the items </param>
        /// <param name="Items_In_Title"> List of items within this title </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        /// <param name="HTML_Skin_Collection"> HTML Web skin collection which controls the overall appearance of this digital library </param>
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        public Group_Add_Volume_MySobekViewer(User_Object User,
            SobekCM_Navigation_Object Current_Mode,
            Item_Lookup_Object All_Items_Lookup,
            SobekCM_Item Current_Item, Aggregation_Code_Manager Code_Manager,
            Dictionary<string, Wordmark_Icon> Icon_Table,
            SobekCM_Skin_Object HTML_Skin,
            SobekCM_Items_In_Title Items_In_Title,
            Language_Support_Info Translator,
			SobekCM_Skin_Collection HTML_Skin_Collection,
            Custom_Tracer Tracer)
            : base(User)
        {
            Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", String.Empty);

            currentMode = Current_Mode;
            item = Current_Item;
            itemList = All_Items_Lookup;
            codeManager = Code_Manager;
            iconList = Icon_Table;
            webSkin = HTML_Skin;
            itemsInTitle = Items_In_Title;
            base.Translator = Translator;
            skins = HTML_Skin_Collection;

            // Set some defaults
            ipRestrict = -1;
            title = String.Empty;
            date = String.Empty;
            level1 = String.Empty;
            level2 = String.Empty;
            level3 = String.Empty;
            level1Order = -1;
            level2Order = -1;
            level3Order = -1;
            hierarchyCopiedFromDate = false;
            message = String.Empty;
            trackingBox = String.Empty;
            bornDigital = false;
            materialRecdDate = null;
            materialRecdNotes = String.Empty;
            dispositionAdvice = -1;
            dispositionAdviceNotes = String.Empty;

            // If the user cannot edit this item, go back
            if (!user.Can_Edit_This_Item(item))
            {
                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                currentMode.Redirect();
                return;
            }

            // Determine the default template code
            string template_code = "addvolume";
            if (!user.Include_Tracking_In_Standard_Forms)
                template_code = "addvolume_notracking";

            // Load this template
            template = Cached_Data_Manager.Retrieve_Template(template_code, Tracer);
            if (template != null)
            {
                Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Found template in cache");
            }
            else
            {
                Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Reading template file");

                // Read this template
                Template_XML_Reader reader = new Template_XML_Reader();
                template = new Template();
                reader.Read_XML(SobekCM_Library_Settings.Base_MySobek_Directory + "templates\\defaults\\" + template_code + ".xml", template, true);

                // Add the current codes to this template
                template.Add_Codes(Code_Manager);

                // Save this into the cache
                Cached_Data_Manager.Store_Template(template_code, template, Tracer);
            }

            // See if there was a hidden request
            string hidden_request = HttpContext.Current.Request.Form["action"] ?? String.Empty;

            // If this was a cancel request do that
            if (hidden_request == "cancel")
            {
                currentMode.Mode = Display_Mode_Enum.Item_Display;
                currentMode.Redirect();
            }
            else if (hidden_request.IndexOf("save") == 0 )
            {
                // Get the VID that used as a source for this
                string vid = HttpContext.Current.Request.Form["base_volume"];

                if (string.IsNullOrEmpty(vid))
                {
                     message = "<span style=\"color: red\"><strong>No base volume selected!</strong></span>";
                }
                else
                {
                    try
                    {
                        // Get a new instance of this item
                        SobekCM_Item saveItem = SobekCM_Item_Factory.Get_Item(Current_Mode.BibID, vid, Icon_Table, null, Tracer);

                        // Clear some values for this item
                        saveItem.VID = String.Empty;
                        saveItem.Divisions.Clear();
                        saveItem.Behaviors.Serial_Info.Clear();
                        saveItem.Bib_Info.Series_Part_Info.Clear();
                        saveItem.Behaviors.Clear_Ticklers();
                        saveItem.Tracking.Internal_Comments = String.Empty;
                        saveItem.Bib_Info.Location.PURL = String.Empty;
                        saveItem.Behaviors.Main_Thumbnail = String.Empty;
                        saveItem.METS_Header.Create_Date = DateTime.Now;
                        saveItem.METS_Header.Modify_Date = saveItem.METS_Header.Create_Date;
                        saveItem.METS_Header.Creator_Software = "SobekCM Web - Online add a volume (derived from VID " + vid + ")";
                        saveItem.METS_Header.Clear_Creator_Individual_Notes();
                        saveItem.METS_Header.Creator_Individual = user.Full_Name;
                        saveItem.Bib_Info.Location.Other_URL = String.Empty;
                        saveItem.Bib_Info.Location.Other_URL_Display_Label = String.Empty;
                        saveItem.Bib_Info.Location.Other_URL_Note = String.Empty;

                        // Save the template changes to this item
                        template.Save_To_Bib(saveItem, user, 1);

                        // Save this item and copy over
                        complete_item_submission(saveItem, Tracer);

                        // Clear the volume list
                        Cached_Data_Manager.Remove_Items_In_Title(saveItem.BibID, Tracer);

                        // Forward differently depending on request
                        switch (hidden_request)
                        {
                            case "save_edit":
                                currentMode.Mode = Display_Mode_Enum.My_Sobek;
                                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Edit_Item_Metadata;
                                currentMode.VID = saveItem.VID;
                                currentMode.Redirect();
                                break;

                            case "save_again":
                                // No redirect, but save values
                                date = saveItem.Bib_Info.Origin_Info.Date_Issued;
                                ipRestrict = saveItem.Behaviors.IP_Restriction_Membership;
                                trackingBox = saveItem.Tracking.Tracking_Box;
                                bornDigital = saveItem.Tracking.Born_Digital;
                                dispositionAdvice = saveItem.Tracking.Disposition_Advice;
                                dispositionAdviceNotes = saveItem.Tracking.Disposition_Advice_Notes;
                                materialRecdDate = saveItem.Tracking.Material_Received_Date;
                                materialRecdNotes = saveItem.Tracking.Material_Received_Notes;
                                if (!hierarchyCopiedFromDate)
                                {
                                    if (saveItem.Behaviors.Serial_Info.Count > 0)
                                    {
                                        level1 = saveItem.Behaviors.Serial_Info[0].Display;
                                        level1Order = saveItem.Behaviors.Serial_Info[0].Order;
                                    }
                                    if (saveItem.Behaviors.Serial_Info.Count > 1)
                                    {
                                        level2 = saveItem.Behaviors.Serial_Info[1].Display;
                                        level2Order = saveItem.Behaviors.Serial_Info[1].Order;
                                    }
                                    if (saveItem.Behaviors.Serial_Info.Count > 2)
                                    {
                                        level3 = saveItem.Behaviors.Serial_Info[2].Display;
                                        level3Order = saveItem.Behaviors.Serial_Info[2].Order;
                                    }
                                }
                                message = message + "<span style=\"color: blue\"><strong>Saved new volume ( " + saveItem.BibID + " : " + saveItem.VID + ")</strong></span>";
                                break;

                            case "save_addfiles":
                                currentMode.Mode = Display_Mode_Enum.My_Sobek;
                                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.File_Management;
                                currentMode.VID = saveItem.VID;
                                currentMode.Redirect();
                                break;

                            default:
                                currentMode.Mode = Display_Mode_Enum.Item_Display;
                                currentMode.VID = saveItem.VID;
                                currentMode.Redirect();
                                break;
                        }

                    }
                    catch ( Exception ee )
                    {
                        message = message + "<br /><span style=\"color: red\"><strong>EXCEPTION CAUGHT!<br /><br />" + ee.Message + "<br /><br />" + ee.StackTrace.Replace("\n","<br />") + "</strong></span>";

                    }
                }
            }
        }
 /// <summary> Get a digital resource for display or for editing </summary>
 /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
 /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
 /// <param name="Base_URL"> Base URL for all the digital resource files for items to display </param>
 /// <param name="Icon_Table"> Dictionary of all the wordmark/icons which can be tagged to the items </param>
 /// <param name="Current_User"> Currently logged on user information (used when editing an item)</param>
 /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
 /// <param name="Current_Item"> [OUT] Built single digital resource ready for displaying or editing </param>
 /// <param name="Current_Page"> [OUT] Build current page for display </param>
 /// <param name="Items_In_Title"> [OUT] List of all the items in this title </param>
 /// <returns> TRUE if successful, otherwise FALSE </returns>
 /// <remarks> This attempts to pull the objects from the cache.  If unsuccessful, it builds the objects from the
 /// database and hands off to the <see cref="Cached_Data_Manager" /> to store in the cache.  If the item must be 
 /// built from scratch, the <see cref="Items.SobekCM_Item_Factory"/> class is utilized. </remarks>
 public bool Get_Item(SobekCM_Navigation_Object Current_Mode,
                      Item_Lookup_Object All_Items_Lookup,
                      string Base_URL, 
                      Dictionary<string, Wordmark_Icon> Icon_Table,
                      User_Object Current_User,
                      Custom_Tracer Tracer, 
                      out SobekCM_Item Current_Item, 
                      out Page_TreeNode Current_Page,
                      out SobekCM_Items_In_Title Items_In_Title )
 {
     return Get_Item(String.Empty, Current_Mode, All_Items_Lookup, Base_URL, Icon_Table, Tracer, Current_User, out Current_Item, out Current_Page, out Items_In_Title);
 }
        /// <summary> Constructor for a new instance of the Delete_Item_MySobekViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="Current_Item"> Individual digital resource to be deleted by the user </param>
        /// <param name="All_Items_Lookup"> Allows individual items to be retrieved by various methods as <see cref="SobekCM.Library.Application_State.Single_Item"/> objects.</param>
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        public Delete_Item_MySobekViewer(User_Object User,
            SobekCM_Navigation_Object Current_Mode, 
			SobekCM_Item Current_Item,
            Item_Lookup_Object All_Items_Lookup,
            Custom_Tracer Tracer)
            : base(User)
        {
            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Delete this item");

            // Save mode and set defaults
            currentMode = Current_Mode;
            item = Current_Item;
            errorCode = -1;

            // Second, ensure this is a logged on user and system administrator before continuing
            Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Validate user permissions" );
            if ((User == null)  || ( !User.LoggedOn ))
            {
                Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "User does not have delete permissions", Custom_Trace_Type_Enum.Error );
                errorCode = 1;
            }
            else
            {
                bool canDelete = false;
                if ((User.Can_Delete_All) || (User.Is_System_Admin))
                {
                    canDelete = true;
                }
                else
                {
                    // In this case, we actually need to build this!
                    try
                    {
            //					SobekCM_Item testItem = SobekCM_Item_Factory.Get_Item(Current_Mode.BibID, Current_Mode.VID, null, Tracer);
                        if (User.Can_Delete_This_Item(item))
                            canDelete = true;
                    }
                    catch
                    {
                        canDelete = false;
                    }
                }

                if (!canDelete)
                {
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "User does not have delete permissions", Custom_Trace_Type_Enum.Error);
                    errorCode = 1;
                }
            }

            // Ensure the item is valid
            if (errorCode == -1)
            {
                Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Validate item exists");
                if (!All_Items_Lookup.Contains_BibID_VID(Current_Mode.BibID, Current_Mode.VID))
                {
                    Tracer.Add_Trace("Delete_Item_MySobekViewer.Constructor", "Item indicated is not valid", Custom_Trace_Type_Enum.Error);
                    errorCode = 2;
                }
            }

             // If this is a postback, handle any events first
            if ((currentMode.isPostBack) && ( errorCode < 0 ))
            {
                Debug.Assert(User != null, "User != null");

                // Pull the standard values
                string save_value = HttpContext.Current.Request.Form["admin_delete_item"];
                string text_value = HttpContext.Current.Request.Form["admin_delete_confirm"];

                // Better say "DELETE", or just send back to the item
                if (( save_value == null ) || ( save_value.ToUpper() != "DELETE" ) || ( text_value.ToUpper() != "DELETE"))
                {
                    HttpContext.Current.Response.Redirect(Current_Mode.Base_URL + currentMode.BibID + "/" + currentMode.VID, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    currentMode.Request_Completed = true;
                }
                else
                {
                    if (currentMode.BibID.ToUpper() == "TEMP000001")
                    {
                        for (int deleteVID = 2124; deleteVID <= 2134; deleteVID++)
                        {
                            currentMode.VID = deleteVID.ToString().PadLeft(5, '0');
                            Delete_Item(User, All_Items_Lookup, Tracer);
                        }
                    }
                    else
                    {
                        Delete_Item(User, All_Items_Lookup, Tracer);
                    }

                }
            }
        }
        /// <summary> Get a digital resource for display or for editing </summary>
        /// <param name="Collection_Code"> Collection code to which this item must belong </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Base_URL"> Base URL for all the digital resource files for items to display </param>
        /// <param name="Icon_Table"> Dictionary of all the wordmark/icons which can be tagged to the items </param>
        /// <param name="Current_User"> Currently logged on user information (used when editing an item)</param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        /// <param name="Current_Item"> [OUT] Built single digital resource ready for displaying or editing </param>
        /// <param name="Current_Page"> [OUT] Build current page for display </param>
        /// <param name="Items_In_Title"> [OUT] List of all the items in this title </param>
        /// <returns> TRUE if successful, otherwise FALSE </returns>
        /// <remarks> This attempts to pull the objects from the cache.  If unsuccessful, it builds the objects from the
        /// database and hands off to the <see cref="Cached_Data_Manager" /> to store in the cache.  If the item must be 
        /// built from scratch, the <see cref="Items.SobekCM_Item_Factory"/> class is utilized. </remarks>
        public bool Get_Item(string Collection_Code, 
                             SobekCM_Navigation_Object Current_Mode, 
                             Item_Lookup_Object All_Items_Lookup, 
                             string Base_URL, 
                             Dictionary<string, Wordmark_Icon> Icon_Table, 
                             Custom_Tracer Tracer, 
                             User_Object Current_User,
                             out SobekCM_Item Current_Item,
                             out Page_TreeNode Current_Page,
                             out SobekCM_Items_In_Title Items_In_Title)
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("SobekCM_Assistant.Get_Item", String.Empty);
            }

            // Initially assign nulls
            Current_Item = null;
            Current_Page = null;
            Items_In_Title = null;

            // Check for legacy reference by itemid
            if ((Current_Mode.BibID.Length == 0) && (Current_Mode.ItemID_DEPRECATED > 0))
            {
                DataRow thisRowInfo = SobekCM_Database.Lookup_Item_By_ItemID(Current_Mode.ItemID_DEPRECATED, Tracer);
                if (thisRowInfo == null)
                {
                    Current_Mode.Invalid_Item = true;
                    return false;
                }

                Current_Mode.Mode = Display_Mode_Enum.Legacy_URL;
                Current_Mode.Error_Message = Current_Mode.Base_URL + thisRowInfo["BibID"] + "/" + thisRowInfo["VID"];
                return false;
            }

            // Must at least have a bib id of the proper length
            if (Current_Mode.BibID.Length < 10)
            {
                Current_Mode.Invalid_Item = true;
                return false;
            }

            // Get the title object for this
            bool item_group_display = false;
            Multiple_Volume_Item dbTitle = All_Items_Lookup.Title_By_Bib(Current_Mode.BibID);
            if (dbTitle == null)
            {
                Current_Mode.Invalid_Item = true;
                return false;
            }

            // Try to get the very basic information about this item, to determine if the
            // bib / vid combination is valid
            Single_Item selected_item = null;

            // Certain mySobek modes only need the item group
            if (( Current_Mode.Mode == Display_Mode_Enum.My_Sobek ) && (( Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Group_Behaviors ) || ( Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Group_Serial_Hierarchy ) || ( Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Group_Add_Volume ) || ( Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Group_AutoFill_Volumes ) || ( Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Group_Mass_Update_Items )))
            {
                item_group_display = true;
            }

            // If this is not a mode that is only item group display, try to pull the item
            if (!item_group_display)
            {
                if ((Current_Mode.VID.Length > 0) && (Current_Mode.VID != "00000"))
                {
                    selected_item = All_Items_Lookup.Item_By_Bib_VID(Current_Mode.BibID, Current_Mode.VID, Tracer);
                }
                else
                {
                    if ((dbTitle.Item_Count == 1) && (Current_Mode.VID != "00000"))
                    {
                        selected_item = All_Items_Lookup.Item_By_Bib_Only(Current_Mode.BibID);
                    }
                    else
                    {
                        item_group_display = true;
                    }
                }
            }

            // If no valid item and not a valid item group display either, return
            if ((selected_item == null) && (!item_group_display))
            {
                Current_Mode.Invalid_Item = true;
                return false;
            }

            // If this is for a single item, return that
            if (selected_item != null)
            {
                // Make sure the VID is set
                Current_Mode.VID = selected_item.VID;

                // Try to get this from the cache
                if ((Current_Mode.Mode == Display_Mode_Enum.My_Sobek) && ( Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Item_Metadata ) && (Current_User != null))
                    Current_Item = Cached_Data_Manager.Retrieve_Digital_Resource_Object(Current_User.UserID, Current_Mode.BibID, Current_Mode.VID, Tracer);
                else
                    Current_Item = Cached_Data_Manager.Retrieve_Digital_Resource_Object( Current_Mode.BibID, Current_Mode.VID, Tracer);

                // If not pulled from the cache, then we will have to build the item
                if (Current_Item == null)
                {
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("SobekCM_Assistant.Get_Item", "Build the item");
                    }

                    Current_Item = SobekCM_Item_Factory.Get_Item(Current_Mode.BibID, Current_Mode.VID, Icon_Table, Tracer);
                    if (Current_Item != null)
                    {
                        if ((Current_Mode.Mode == Display_Mode_Enum.My_Sobek) && (Current_Mode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Item_Metadata) && (Current_User != null))
                        {
                            string note_to_add = "Online edit by " + Current_User.Full_Name + " ( " + DateTime.Now.ToShortDateString() + " )";
                            Current_Item.METS_Header.Add_Creator_Individual_Notes( note_to_add );
                            Cached_Data_Manager.Store_Digital_Resource_Object(Current_User.UserID, Current_Mode.BibID, Current_Mode.VID, Current_Item, Tracer);
                        }
                        else
                            Cached_Data_Manager.Store_Digital_Resource_Object(Current_Mode.BibID, Current_Mode.VID, Current_Item, Tracer);
                    }
                }
                else
                {
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("SobekCM_Assistant.Get_Item", "Item found in the cache");
                    }
                }

                // If an item was requested and none was found, go to the current home
                if ((Current_Item == null))
                {
                    if (Tracer != null && !Tracer.Enabled)
                    {
                        Current_Mode.Mode = Display_Mode_Enum.Aggregation_Home;
                        return false;
                    }
                    return false;
                }

                // Get the page to display (printing has its own specification of page(s) to display)
                if (Current_Mode.Mode != Display_Mode_Enum.Item_Print)
                {
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("SobekCM_Assistant.Get_Item", "Get the current page");
                    }
                    Current_Page = SobekCM_Item_Factory.Get_Current_Page(Current_Item, Current_Mode.Page, Tracer);
                }
            }
            else if (item_group_display)
            {
                // Try to get this from the cache
                Current_Item = Cached_Data_Manager.Retrieve_Digital_Resource_Object(Current_Mode.BibID, Tracer);

                // Have to build this item group information then
                if (Current_Item == null)
                {
                    string bibID = Current_Mode.BibID;
                    SobekCM_Item_Factory.Get_Item_Group(bibID, Tracer, out Items_In_Title, out Current_Item );
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("SobekCM_Assistant.Get_Item", "TEST LOG ENTRY");
                    }

                    if (Current_Item == null)
                    {
                        Exception ee = SobekCM_Database.Last_Exception;
                        if (Tracer != null)
                            Tracer.Add_Trace("SobekCM_Assistant.Get_Item", ee != null ? ee.Message : "NO DATABASE EXCEPTION", Custom_Trace_Type_Enum.Error);

                        Current_Mode.Invalid_Item = true;
                        return false;
                    }

                    // Put this back on the cache
                    Current_Item.METS_Header.RecordStatus_Enum = METS_Record_Status.BIB_LEVEL;
                    Cached_Data_Manager.Store_Digital_Resource_Object(bibID, Current_Item, Tracer);
                    Cached_Data_Manager.Store_Items_In_Title(bibID, Items_In_Title, Tracer);
                }
            }

            return true;
        }
Esempio n. 27
0
        /// <summary> Refreshes the item list and aggregation/greenstone code information from the database on a regular basis </summary>
        /// <param name="Code_Manager"> [REF] List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library </param>
        /// <returns> TRUE if successful, otherwise FALSE </returns>
        public static bool Refresh_Item_List_And_Aggregation_Codes(ref Aggregation_Code_Manager Code_Manager, ref Item_Lookup_Object All_Items_Lookup)
        {
            try
            {
                // Load SobekCM Codes to Greenstone Codes conversion again
                if (Code_Manager != null)
                {
                    lock (Code_Manager)
                    {
                        SobekCM_Database.Populate_Code_Manager(Code_Manager, null);
                    }
                }
                else
                {
                    Code_Manager = new Aggregation_Code_Manager();
                    SobekCM_Database.Populate_Code_Manager(Code_Manager, null);
                }

                //lock (item_list_lock_object)
                //{
                //    if (All_Items_Lookup == null)
                //        All_Items_Lookup = new Item_Lookup_Object();

                //    // Have the database popoulate the little bit of bibid/vid information we retain
                //    SobekCM_Database.Populate_Item_Lookup_Object(true, All_Items_Lookup, null);
                //}

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 28
0
        /// <summary> Verifies that each global object is built and builds them upon request </summary>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        /// <param name="Reload_All"> Flag indicates if everything should be reloaded/repopulated</param>
        /// <param name="Skins"> [REF] Collection of all the web skins </param>
        /// <param name="Translator"> [REF] Language support object which handles simple translational duties </param>
        /// <param name="Code_Manager"> [REF] List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Icon_Dictionary"> [REF] Dictionary of information about every wordmark/icon in this digital library </param>
        /// <param name="Stats_Date_Range"> [REF] Object contains the start and end dates for the statistical data in the database </param>
        /// <param name="Thematic_Headings"> [REF] Headings under which all the highlighted collections on the main home page are organized </param>
        /// <param name="Aggregation_Aliases"> [REF] List of all existing aliases for existing aggregations </param>
        /// <param name="IP_Restrictions"> [REF] List of all IP Restriction ranges in use by this digital library </param>
        /// <param name="URL_Portals"> [REF] List of all web portals into this system </param>
        /// <param name="Mime_Types">[REF] Dictionary of MIME types by extension</param>
        public static void Build_Application_State(Custom_Tracer Tracer, bool Reload_All,
                                                   ref SobekCM_Skin_Collection Skins, ref Language_Support_Info Translator,
                                                   ref Aggregation_Code_Manager Code_Manager, ref Item_Lookup_Object All_Items_Lookup,
                                                   ref Dictionary <string, Wordmark_Icon> Icon_Dictionary,
                                                   ref Statistics_Dates Stats_Date_Range,
                                                   ref List <Thematic_Heading> Thematic_Headings,
                                                   ref Dictionary <string, string> Aggregation_Aliases,
                                                   ref IP_Restriction_Ranges IP_Restrictions,
                                                   ref Portal_List URL_Portals,
                                                   ref Dictionary <string, Mime_Type_Info> Mime_Types)
        {
            // Should we reload the data from the exteral configuraiton file?
            if (Reload_All)
            {
                SobekCM_Library_Settings.Read_Configuration_File();
                SobekCM_Database.Connection_String = SobekCM_Library_Settings.Database_Connection_String;
                SobekCM_Library_Settings.Refresh(SobekCM_Database.Get_Settings_Complete(null));
            }

            // If there is no database connection string, there is a problem
            if (String.IsNullOrEmpty(SobekCM_Library_Settings.Database_Connection_String))
            {
                throw new ApplicationException("Missing database connection string!");
            }

            // Set the database connection strings
            Resource_Object.Database.SobekCM_Database.Connection_String = SobekCM_Library_Settings.Database_Connection_String;
            SobekCM_Database.Connection_String = SobekCM_Library_Settings.Database_Connection_String;

            // Set the workflow and disposition types
            if ((SobekCM_Library_Settings.Need_Workflow_And_Disposition_Types) || (Reload_All))
            {
                SobekCM_Library_Settings.Set_Workflow_And_Disposition_Types(SobekCM_Database.All_WorkFlow_Types, SobekCM_Database.All_Possible_Disposition_Types);
            }

            // Set the metadata types
            if ((SobekCM_Library_Settings.Need_Metadata_Types) || (Reload_All))
            {
                SobekCM_Library_Settings.Set_Metadata_Types(SobekCM_Database.Get_Metadata_Fields(null));
            }

            // Set the search stop words
            if ((SobekCM_Library_Settings.Need_Search_Stop_Words) || (Reload_All))
            {
                SobekCM_Library_Settings.Search_Stop_Words = SobekCM_Database.Search_Stop_Words(Tracer);
            }

            // Check the list of thematic headings
            if ((Thematic_Headings == null) || (Reload_All))
            {
                if (Thematic_Headings != null)
                {
                    lock (Thematic_Headings)
                    {
                        if (!SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer))
                        {
                            Thematic_Headings = null;
                            throw SobekCM_Database.Last_Exception;
                        }
                    }
                }
                else
                {
                    Thematic_Headings = new List <Thematic_Heading>();
                    if (!SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer))
                    {
                        Thematic_Headings = null;
                        throw SobekCM_Database.Last_Exception;
                    }
                }
            }

            // Check the list of forwardings
            if ((Aggregation_Aliases == null) || (Reload_All))
            {
                if (Aggregation_Aliases != null)
                {
                    lock (Aggregation_Aliases)
                    {
                        SobekCM_Database.Populate_Aggregation_Aliases(Aggregation_Aliases, Tracer);
                    }
                }
                else
                {
                    Aggregation_Aliases = new Dictionary <string, string>();
                    SobekCM_Database.Populate_Aggregation_Aliases(Aggregation_Aliases, Tracer);
                }
            }

            // Check the list of constant skins
            if ((Skins == null) || (Skins.Count == 0) || (Reload_All))
            {
                if (Skins != null)
                {
                    lock (Skins)
                    {
                        SobekCM_Skin_Collection_Builder.Populate_Default_Skins(Skins, Tracer);
                    }
                }
                else
                {
                    Skins = new SobekCM_Skin_Collection();
                    SobekCM_Skin_Collection_Builder.Populate_Default_Skins(Skins, Tracer);
                }
            }

            // Check the list of all web portals
            if ((URL_Portals == null) || (URL_Portals.Count == 0) || (Reload_All))
            {
                if (URL_Portals != null)
                {
                    lock (URL_Portals)
                    {
                        SobekCM_Database.Populate_URL_Portals(URL_Portals, Tracer);
                    }
                }
                else
                {
                    URL_Portals = new Portal_List();
                    SobekCM_Database.Populate_URL_Portals(URL_Portals, Tracer);
                }
            }

            // Check the translation table has been loaded
            if ((Translator == null) || (Reload_All))
            {
                // Get the translation hashes into memory
                if (Translator != null)
                {
                    lock (Translator)
                    {
                        SobekCM_Database.Populate_Translations(Translator, Tracer);
                    }
                }
                else
                {
                    Translator = new Language_Support_Info();
                    SobekCM_Database.Populate_Translations(Translator, Tracer);
                }
            }

            // Check that the conversion from SobekCM Codes to Greenstone Codes has been loaded
            if ((Code_Manager == null) || (Reload_All))
            {
                if (Code_Manager != null)
                {
                    lock (Code_Manager)
                    {
                        SobekCM_Database.Populate_Code_Manager(Code_Manager, Tracer);
                    }
                }
                else
                {
                    Code_Manager = new Aggregation_Code_Manager();
                    SobekCM_Database.Populate_Code_Manager(Code_Manager, Tracer);
                }
            }

            // Check the statistics date range information
            if ((Stats_Date_Range == null) || (Reload_All))
            {
                if (Stats_Date_Range != null)
                {
                    // Get the translation hashes into memory
                    lock (Stats_Date_Range)
                    {
                        SobekCM_Database.Populate_Statistics_Dates(Stats_Date_Range, Tracer);
                    }
                }
                else
                {
                    Stats_Date_Range = new Statistics_Dates();
                    SobekCM_Database.Populate_Statistics_Dates(Stats_Date_Range, Tracer);
                }
            }

            // Get the Icon list
            if ((Icon_Dictionary == null) || (Reload_All))
            {
                if (Icon_Dictionary != null)
                {
                    // Get the translation hashes into memory
                    lock (Icon_Dictionary)
                    {
                        SobekCM_Database.Populate_Icon_List(Icon_Dictionary, Tracer);
                    }
                }
                else
                {
                    Icon_Dictionary = new Dictionary <string, Wordmark_Icon>();
                    SobekCM_Database.Populate_Icon_List(Icon_Dictionary, Tracer);
                }
            }

            // Check the list of ip range restrictions
            if ((IP_Restrictions == null) || (Reload_All))
            {
                if (IP_Restrictions != null)
                {
                    lock (IP_Restrictions)
                    {
                        DataTable ipRestrictionTbl = SobekCM_Database.Get_IP_Restriction_Ranges(Tracer);
                        if (ipRestrictionTbl != null)
                        {
                            IP_Restrictions.Populate_IP_Ranges(ipRestrictionTbl);
                        }
                    }
                }
                else
                {
                    DataTable ipRestrictionTbl = SobekCM_Database.Get_IP_Restriction_Ranges(Tracer);
                    if (ipRestrictionTbl != null)
                    {
                        IP_Restrictions = new IP_Restriction_Ranges();
                        IP_Restrictions.Populate_IP_Ranges(ipRestrictionTbl);
                    }
                }
            }


            // Get the MIME type list
            if ((Mime_Types == null) || (Reload_All))
            {
                if (Mime_Types != null)
                {
                    // Get the translation hashes into memory
                    lock (Mime_Types)
                    {
                        SobekCM_Database.Populate_MIME_List(Mime_Types, Tracer);
                    }
                }
                else
                {
                    Mime_Types = new Dictionary <string, Mime_Type_Info>();
                    SobekCM_Database.Populate_MIME_List(Mime_Types, Tracer);
                }
            }
        }
        /// <summary> Performs a search ( or retrieves the search results from the cache ) and outputs the results and search url used  </summary>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Aggregation_Object"> Object for the current aggregation object, against which this search is performed </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        /// <param name="Complete_Result_Set_Info"> [OUT] Information about the entire set of results </param>
        /// <param name="Paged_Results"> [OUT] List of search results for the requested page of results </param>
        public void Get_Search_Results(SobekCM_Navigation_Object Current_Mode,
                                       Item_Lookup_Object All_Items_Lookup,
                                       Item_Aggregation Aggregation_Object,
                                       Custom_Tracer Tracer,
                                       out Search_Results_Statistics Complete_Result_Set_Info,
                                       out List<iSearch_Title_Result> Paged_Results )
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("SobekCM_Assistant.Get_Search_Results", String.Empty);
            }

            // Set output initially to null
            Paged_Results = null;
            Complete_Result_Set_Info = null;

            // Get the sort
            int sort = Current_Mode.Sort;
            if ((sort != 0) && (sort != 1) && (sort != 2) && (sort != 10) && (sort != 11))
                sort = 0;

            // Depending on type of search, either go to database or Greenstone
            if (Current_Mode.Search_Type == Search_Type_Enum.Map)
            {
                try
                {
                    double lat1 = 1000;
                    double long1 = 1000;
                    double lat2 = 1000;
                    double long2 = 1000;
                    string[] terms = Current_Mode.Coordinates.Split(",".ToCharArray());
                    if (terms.Length < 2)
                    {
                        Current_Mode.Mode = Display_Mode_Enum.Search;
                        HttpContext.Current.Response.Redirect(Current_Mode.Redirect_URL());
                    }
                    if (terms.Length < 4)
                    {
                        lat1 = Convert.ToDouble(terms[0]);
                        lat2 = lat1;
                        long1 = Convert.ToDouble(terms[1]);
                        long2 = long1;
                    }
                    if (terms.Length >= 4)
                    {
                        if (terms[0].Length > 0)
                            lat1 = Convert.ToDouble(terms[0]);
                        if (terms[1].Length > 0)
                            long1 = Convert.ToDouble(terms[1]);
                        if (terms[2].Length > 0)
                            lat2 = Convert.ToDouble(terms[2]);
                        if (terms[3].Length > 0)
                            long2 = Convert.ToDouble(terms[3]);
                    }

                    // If neither point is valid, return
                    if (((lat1 == 1000) || (long1 == 1000)) && ((lat2 == 1000) || (long2 == 1000)))
                    {
                        Current_Mode.Mode = Display_Mode_Enum.Search;
                        HttpContext.Current.Response.Redirect(Current_Mode.Redirect_URL());
                    }

                    // If just the first point is valid, use that
                    if ((lat2 == 1000) || (long2 == 1000))
                    {
                        lat2 = lat1;
                        long2 = long1;
                    }

                    // If just the second point is valid, use that
                    if ((lat1 == 1000) || (long1 == 1000))
                    {
                        lat1 = lat2;
                        long1 = long2;
                    }

                    // Perform the search against the database
                    try
                    {
                        // Try to pull more than one page, so we can cache the next page or so

                        Multiple_Paged_Results_Args returnArgs = SobekCM_Database.Get_Items_By_Coordinates(Current_Mode.Aggregation, lat1, long1, lat2, long2, false, 20, Current_Mode.Page, sort, false, new List<short>(), true, Tracer);
                        List<List<iSearch_Title_Result>> pagesOfResults = returnArgs.Paged_Results;
                        Complete_Result_Set_Info = returnArgs.Statistics;

                        if ((pagesOfResults != null) && (pagesOfResults.Count > 0))
                            Paged_Results = pagesOfResults[0];
                    }
                    catch (Exception ee)
                    {
                        // Next, show the message to the user
                        Current_Mode.Mode = Display_Mode_Enum.Error;
                        string error_message = ee.Message;
                        if (error_message.ToUpper().IndexOf("TIMEOUT") >= 0)
                        {
                            error_message = "Database Timeout Occurred<br /><br />Try again in a few minutes.<br /><br />";
                        }
                        Current_Mode.Error_Message = error_message;
                        Current_Mode.Caught_Exception = ee;
                    }
                }
                catch
                {
                    Current_Mode.Mode = Display_Mode_Enum.Search;
                    HttpContext.Current.Response.Redirect(Current_Mode.Redirect_URL());
                }
            }
            else
            {
                List<string> terms = new List<string>();
                List<string> web_fields = new List<string>();

                // Split the terms correctly ( only use the database stop words for the split if this will go to the database ultimately)
                if ((Current_Mode.Search_Type == Search_Type_Enum.Full_Text) || (Current_Mode.Search_Fields.IndexOf("TX") >= 0))
                {
                    Split_Clean_Search_Terms_Fields(Current_Mode.Search_String, Current_Mode.Search_Fields, Current_Mode.Search_Type, terms, web_fields, null, Current_Mode.Search_Precision, ',');
                }
                else
                {
                    Split_Clean_Search_Terms_Fields(Current_Mode.Search_String, Current_Mode.Search_Fields, Current_Mode.Search_Type, terms, web_fields, SobekCM_Library_Settings.Search_Stop_Words, Current_Mode.Search_Precision, ',');
                }

                // Get the count that will be used
                int actualCount = Math.Min(terms.Count, web_fields.Count);

                // Determine if this is a special search type which returns more rows and is not cached.
                // This is used to return the results as XML and DATASET
                bool special_search_type = false;
                int results_per_page = 20;
                if ((Current_Mode.Writer_Type == Writer_Type_Enum.XML) || (Current_Mode.Writer_Type == Writer_Type_Enum.DataSet))
                {
                    results_per_page = 1000;
                    special_search_type = true;
                    sort = 2; // Sort by BibID always for these
                }

                // Set the flags for how much data is needed.  (i.e., do we need to pull ANYTHING?  or
                // perhaps just the next page of results ( as opposed to pulling facets again).
                bool need_search_statistics = true;
                bool need_paged_results = true;
                if (!special_search_type)
                {
                    // Look to see if the search statistics are available on any cache..
                    Complete_Result_Set_Info = Cached_Data_Manager.Retrieve_Search_Result_Statistics(Current_Mode, actualCount, web_fields, terms, Tracer);
                    if (Complete_Result_Set_Info != null)
                        need_search_statistics = false;

                    // Look to see if the paged results are available on any cache..
                    Paged_Results = Cached_Data_Manager.Retrieve_Search_Results(Current_Mode, sort, actualCount, web_fields, terms, Tracer);
                    if (Paged_Results != null)
                        need_paged_results = false;
                }

                // If both were retrieved, do nothing else
                if ((need_paged_results) || (need_search_statistics))
                {
                    // Should this pull the search from the database, or from greenstone?
                    if ((Current_Mode.Search_Type == Search_Type_Enum.Full_Text) || (Current_Mode.Search_Fields.IndexOf("TX") >= 0))
                    {
                        try
                        {
                            // Perform the search against greenstone
                            Search_Results_Statistics recomputed_search_statistics;
                            Perform_Solr_Search(Tracer, terms, web_fields, actualCount, Current_Mode.Aggregation, Current_Mode.Page, sort, results_per_page, out recomputed_search_statistics, out Paged_Results);
                            if (need_search_statistics)
                                Complete_Result_Set_Info = recomputed_search_statistics;
                        }
                        catch (Exception ee)
                        {
                            Current_Mode.Mode = Display_Mode_Enum.Error;
                            Current_Mode.Error_Message = "Unable to perform search at this time";
                            Current_Mode.Caught_Exception = ee;
                        }

                        // If this was a special search, don't cache this
                        if (!special_search_type)
                        {
                            // Cache the search statistics, if it was needed
                            if ((need_search_statistics) && (Complete_Result_Set_Info != null))
                            {
                                Cached_Data_Manager.Store_Search_Result_Statistics(Current_Mode, actualCount, web_fields, terms, Complete_Result_Set_Info, Tracer);
                            }

                            // Cache the search results
                            if ((need_paged_results) && (Paged_Results != null))
                            {
                                Cached_Data_Manager.Store_Search_Results(Current_Mode, sort, actualCount, web_fields, terms, Paged_Results, Tracer);
                            }
                        }
                    }
                    else
                    {
                        // Try to pull more than one page, so we can cache the next page or so
                        List<List<iSearch_Title_Result>> pagesOfResults = new List<List<iSearch_Title_Result>>();

                        // Perform the search against the database
                        try
                        {
                            Search_Results_Statistics recomputed_search_statistics;
                            Perform_Database_Search(Tracer, terms, web_fields, actualCount, Current_Mode, sort, Aggregation_Object, All_Items_Lookup, results_per_page, !special_search_type, out recomputed_search_statistics, out pagesOfResults, need_search_statistics);
                            if (need_search_statistics)
                                Complete_Result_Set_Info = recomputed_search_statistics;

                            if ((pagesOfResults != null) && (pagesOfResults.Count > 0))
                                Paged_Results = pagesOfResults[0];
                        }
                        catch (Exception ee)
                        {
                            // Next, show the message to the user
                            Current_Mode.Mode = Display_Mode_Enum.Error;
                            string error_message = ee.Message;
                            if (error_message.ToUpper().IndexOf("TIMEOUT") >= 0)
                            {
                                error_message = "Database Timeout Occurred<br /><br />Try narrowing your search by adding more terms <br />or putting quotes around your search.<br /><br />";
                            }
                            Current_Mode.Error_Message = error_message;
                            Current_Mode.Caught_Exception = ee;
                        }

                        // If this was a special search, don't cache this
                        if (!special_search_type)
                        {
                            // Cache the search statistics, if it was needed
                            if ((need_search_statistics) && (Complete_Result_Set_Info != null))
                            {
                                Cached_Data_Manager.Store_Search_Result_Statistics(Current_Mode, actualCount, web_fields, terms, Complete_Result_Set_Info, Tracer);
                            }

                            // Cache the search results
                            if ((need_paged_results) && (pagesOfResults != null))
                            {
                                Cached_Data_Manager.Store_Search_Results(Current_Mode, sort, actualCount, web_fields, terms, pagesOfResults, Tracer);
                            }
                        }
                    }
                }
            }
        }
        /// <summary> Refreshes the item list and aggregation/greenstone code information from the database on a regular basis </summary>
        /// <param name="Code_Manager"> [REF] List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="All_Items_Lookup"> [REF] Lookup object used to pull basic information about any item loaded into this library </param>
        /// <returns> TRUE if successful, otherwise FALSE </returns>
        public static bool Refresh_Item_List_And_Aggregation_Codes(ref Aggregation_Code_Manager Code_Manager, ref Item_Lookup_Object All_Items_Lookup )
        {
            try
            {
                // Load SobekCM Codes to Greenstone Codes conversion again
                if (Code_Manager != null)
                {
                    lock (Code_Manager)
                    {
                        SobekCM_Database.Populate_Code_Manager(Code_Manager, null);
                    }
                }
                else
                {
                    Code_Manager = new Aggregation_Code_Manager();
                    SobekCM_Database.Populate_Code_Manager(Code_Manager, null);
                }

                //lock (item_list_lock_object)
                //{
                //    if (All_Items_Lookup == null)
                //        All_Items_Lookup = new Item_Lookup_Object();

                //    // Have the database popoulate the little bit of bibid/vid information we retain
                //    SobekCM_Database.Populate_Item_Lookup_Object(true, All_Items_Lookup, null);
                //}

                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary> Find the static html file to display for an item view request, when requested by a search engine robot for indexing </summary>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="All_Items_Lookup"> Lookup object used to pull basic information about any item loaded into this library </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        /// <returns> Location for the static html file to display for this item view request </returns>
        public string Get_Item_Static_HTML(SobekCM_Navigation_Object Current_Mode, Item_Lookup_Object All_Items_Lookup, Custom_Tracer Tracer)
        {
            // Must at least have a bib id of the proper length
            if (Current_Mode.BibID.Length < 10)
            {
                Current_Mode.Invalid_Item = true;
                return String.Empty;
            }

            // Get the title object for this
            Multiple_Volume_Item dbTitle = All_Items_Lookup.Title_By_Bib(Current_Mode.BibID);
            if (dbTitle == null)
            {
                Current_Mode.Invalid_Item = true;
                return String.Empty;
            }

            // Try to get the very basic information about this item, to determine if the
            // bib / vid combination is valid
            Single_Item selected_item = null;
            if (Current_Mode.VID.Length > 0)
            {
                selected_item = All_Items_Lookup.Item_By_Bib_VID(Current_Mode.BibID, Current_Mode.VID, Tracer);
            }
            else
            {
                if (dbTitle.Item_Count == 1)
                {
                    selected_item = All_Items_Lookup.Item_By_Bib_Only(Current_Mode.BibID);
                }
            }

            // If no valid item and not a valid item group display either, return
            if (selected_item == null)
            {
                Current_Mode.Invalid_Item = true;
                return String.Empty;
            }

            // Set the title to the info browse, just to store it somewhere
            Current_Mode.Info_Browse_Mode = selected_item.Title;

            // Get the text for this item
            string bibid = Current_Mode.BibID;
            string vid = selected_item.VID.PadLeft(5, '0');
            Current_Mode.VID = vid;
            string base_image_url = SobekCM_Library_Settings.Base_Data_Directory + bibid.Substring(0, 2) + "\\" + bibid.Substring(2, 2) + "\\" + bibid.Substring(4, 2) + "\\" + bibid.Substring(6, 2) + "\\" + bibid.Substring(8, 2) + "\\" + bibid + "_" + vid + ".html";
            return base_image_url;
        }
        /// <summary> Constructor for a new instance of the Edit_Item_Metadata_MySobekViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="All_Items_Lookup"> Allows individual items to be retrieved by various methods as <see cref="Single_Item"/> objects.</param>
        /// <param name="Current_Item"> Individual digital resource to be edited by the user </param>
        /// <param name="Code_Manager"> Code manager contains the list of all valid aggregation codes </param>
        /// <param name="HTML_Skin"> HTML Web skin which controls the overall appearance of this digital library </param>
        /// <param name="Icon_Table"> Dictionary of all the wordmark/icons which can be tagged to the items </param>
        /// <param name="HTML_Skin_Collection"> HTML Web skin collection which controls the overall appearance of this digital library </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        public Edit_Item_Metadata_MySobekViewer(User_Object User,
            SobekCM_Navigation_Object Current_Mode,
            Item_Lookup_Object All_Items_Lookup,
            SobekCM_Item Current_Item, Aggregation_Code_Manager Code_Manager,
            Dictionary<string, Wordmark_Icon> Icon_Table,
            SobekCM_Skin_Object HTML_Skin,
            Language_Support_Info Translator,
            SobekCM_Skin_Collection HTML_Skin_Collection,
            Custom_Tracer Tracer)
            : base(User)
        {
            Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", String.Empty);

            currentMode = Current_Mode;
            item = Current_Item;
            itemList = All_Items_Lookup;
            codeManager = Code_Manager;
            iconList = Icon_Table;
            webSkin = HTML_Skin;
            popUpFormsHtml = String.Empty;
            delayed_popup = String.Empty;
            base.Translator = Translator;
            skins = HTML_Skin_Collection;

            // If the user cannot edit this item, go back
            if (!user.Can_Edit_This_Item( item ))
            {
                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                HttpContext.Current.Response.Redirect(currentMode.Redirect_URL());
            }

            // Is this a project
            isProject = item.Bib_Info.SobekCM_Type == TypeOfResource_SobekCM_Enum.Project;

            string template_code = user.Edit_Template_Code;
            if ((isProject) || (item.Contains_Complex_Content) || (item.Using_Complex_Template))
            {
                template_code = user.Edit_Template_MARC_Code;
            }
            template = Cached_Data_Manager.Retrieve_Template(template_code, Tracer);
            if (template != null)
            {
                Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Found template in cache");
            }
            else
            {
                Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Reading template file");

                // Read this template
                Template_XML_Reader reader = new Template_XML_Reader();
                template = new Template();
                reader.Read_XML( SobekCM_Library_Settings.Base_MySobek_Directory + "templates\\edit\\" + template_code + ".xml", template, true);

                // Add the current codes to this template
                template.Add_Codes(Code_Manager);

                // Save this into the cache
                Cached_Data_Manager.Store_Template(template_code, template, Tracer);
            }

            // Get the current page number, or default to 1
            page = 1;
            if (currentMode.My_Sobek_SubMode.Length > 0)
            {
                if ((currentMode.My_Sobek_SubMode == "preview") || (currentMode.My_Sobek_SubMode == "marc") || (currentMode.My_Sobek_SubMode == "mets"))
                {
                    page = 0;
                }
                else
                {
                    page = 1;
                    bool isNumber = currentMode.My_Sobek_SubMode.All(Char.IsNumber);
                    if (isNumber)
                    {
                        if (isProject)
                            Double.TryParse(currentMode.My_Sobek_SubMode[0].ToString(), out page);
                        else
                            Double.TryParse(currentMode.My_Sobek_SubMode, out page);
                    }
                    else if ( isProject )
                    {
                        if ( Char.IsNumber(currentMode.My_Sobek_SubMode[0]))
                            Double.TryParse(currentMode.My_Sobek_SubMode[0].ToString(), out page);
                    }
                }
            }

            // Handle post backs
            if (Current_Mode.isPostBack)
            {
                // See if there was a hidden request
                string hidden_request = HttpContext.Current.Request.Form["new_element_requested"] ?? String.Empty;

                // If this was a cancel request do that
                if (hidden_request == "cancel")
                {
                    if (isProject)
                    {
                        Cached_Data_Manager.Remove_Project(user.UserID, item.BibID, null);

                        currentMode.Mode = Display_Mode_Enum.Administrative;
                        currentMode.Admin_Type = Admin_Type_Enum.Default_Metadata;
                        currentMode.My_Sobek_SubMode = String.Empty;
                        currentMode.Redirect();
                    }
                    else
                    {
                        Cached_Data_Manager.Remove_Digital_Resource_Object(user.UserID, item.BibID, item.VID, null);

                        currentMode.Mode = Display_Mode_Enum.Item_Display;
                        currentMode.Redirect();
                    }
                    return;
                }

                // Save these changes to bib
                template.Save_To_Bib(item, user, ((int) page));

                // See if the user asked for a new element of a complex form type
                delayed_popup = String.Empty;
                switch (hidden_request.Trim())
                {
                    case "name":
                        delayed_popup = "name";
                        item.Bib_Info.Add_Named_Entity(String.Empty).Name_Type = Name_Info_Type_Enum.personal;
                        break;

                    case "title":
                        delayed_popup = "title";
                        item.Bib_Info.Add_Other_Title(String.Empty, Title_Type_Enum.alternative);
                        break;

                    case "subject":
                        delayed_popup = "subject";
                        item.Bib_Info.Add_Subject();
                        break;

                    case "spatial":
                        delayed_popup = "spatial";
                        item.Bib_Info.Add_Hierarchical_Geographic_Subject();
                        break;

                    case "relateditem":
                        delayed_popup = "relateditem";
                        item.Bib_Info.Add_Related_Item(new Related_Item_Info());
                        break;

                    case "save":
                        Complete_Item_Save();
                        break;

                    case "complicate":
                        item.Using_Complex_Template = true;
                        HttpContext.Current.Response.Redirect( "?" + HttpContext.Current.Request.QueryString, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        currentMode.Request_Completed = true;
                        return;

                    case "simplify":
                        item.Using_Complex_Template = false;
                        HttpContext.Current.Response.Redirect( "?" + HttpContext.Current.Request.QueryString, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        currentMode.Request_Completed = true;
                        return;
                }

                // Was this for a new page?
                if (hidden_request.IndexOf("newpage") == 0)
                {
                    string page_requested = hidden_request.Replace("newpage", "");
                    if (page_requested != currentMode.My_Sobek_SubMode)
                    {
                        // forward to requested page
                        currentMode.My_Sobek_SubMode = page_requested;
                        if (currentMode.My_Sobek_SubMode == "0")
                            currentMode.My_Sobek_SubMode = "preview";
                        if (isProject)
                            currentMode.My_Sobek_SubMode = page_requested + item.BibID;

                        HttpContext.Current.Response.Redirect(currentMode.Redirect_URL() + "#template", false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        currentMode.Request_Completed = true;
                    }
                }
            }
        }