/// <summary> This is an opportunity to write HTML directly into the main form, without
        /// using the pop-up html form architecture </summary>
        /// <param name="Output"> Textwriter to write the pop-up form HTML for this viewer </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        /// <remarks> This text will appear within the ItemNavForm form tags </remarks>
        public override void Write_ItemNavForm_Closing(TextWriter Output, Custom_Tracer Tracer)
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("New_TEI_MySobekViewer.Write_ItemNavForm_Closing", "");
            }

            // Add the hidden fields first
            Output.WriteLine("<!-- Hidden field is used for postbacks to indicate what to save and reset -->");
            Output.WriteLine("<input type=\"hidden\" id=\"action\" name=\"action\" value=\"\" />");
            Output.WriteLine("<input type=\"hidden\" id=\"phase\" name=\"phase\" value=\"\" />");
            Output.WriteLine("<script type=\"text/javascript\" src=\"" + Static_Resources_Gateway.Sobekcm_Metadata_Js + "\" ></script>");

            #region Add the agreement HTML for the first step

            if (currentProcessStep == 1)
            {
                Output.WriteLine("<div class=\"sbkMySobek_HomeText\" >");
                Output.WriteLine("<br />");
                if (completeTemplate.Permissions_Agreement.Length > 0)
                {
                    Output.WriteLine("<h2>Step 1 of " + totalTemplatePages + ": Grant of Permission</h2>");

                    Output.WriteLine("<blockquote>You must read and accept the below permissions to continue.<br /><br />");
                    Output.WriteLine(completeTemplate.Permissions_Agreement.Replace("<%BASEURL%>", RequestSpecificValues.Current_Mode.Base_URL).Replace("[%BASEURL%]", RequestSpecificValues.Current_Mode.Base_URL).Replace("[%SYSTEMNAME%]", RequestSpecificValues.Current_Mode.Instance_Name));
                    //     Output.WriteLine("<p>Please review the <a href=\"?g=ufirg&amp;m=hitauthor_faq#policies&amp;n=gs\">Policies</A> if you have any questions or please contact us with any questions prior to submitting files. </p>\n");
                    Output.WriteLine("<table id=\"sbkNgi_GrantPermissionsAgreeSubTable\">");
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td>You must read and accept the above permissions agreement to continue. &nbsp; &nbsp; </td>");
                    Output.WriteLine("    <td>");
                    Output.WriteLine("        <button onclick=\"return new_item_cancel();\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> CANCEL </button> &nbsp; &nbsp; ");
                    Output.WriteLine("        <button onclick=\"return new_item_next_phase(2);\" class=\"sbkMySobek_BigButton\"> ACCEPT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                    Output.WriteLine("    </td>");
                    Output.WriteLine("  </tr>");
                    Output.WriteLine("</table>");
                    Output.WriteLine("</blockquote><br />");

                }

                Output.WriteLine("<br />");
                Output.WriteLine("</div>");
            }

            #endregion

            #region Add the HTML to select the mapping, css, and xslt

            if (currentProcessStep == 3)
            {
                Output.WriteLine("<div class=\"sbkMySobek_HomeText\" >");
                Output.WriteLine("<br />");

                Output.WriteLine("<h2>Step 3 of " + totalTemplatePages + ": Select Mapping and Display Parameters</h2>");

                Output.WriteLine("Select the metadata mapping for importing metadata from your TEI and select the XSLT and CSS to display your TEI file within this system.<br /><br />");

                Output.WriteLine("<table class=\"sbkMySobek_TemplateTbl\" cellpadding=\"4px\" >");
                Output.WriteLine("  <tr>");
                Output.WriteLine("    <td colspan=\"3\" class=\"sbkMySobek_TemplateTblTitle_first\">Metadata Mapping</td>");
                Output.WriteLine("  </tr>");

                // Get the list of Mapping files that exist and this user is enabled for
                List<string> mapping_files = new List<string>();
                foreach (string thisSettingKey in RequestSpecificValues.Current_User.Settings.Keys)
                {
                    if (thisSettingKey.IndexOf("TEI.MAPPING.") == 0)
                    {
                        // Only show enabled options
                        string enabled = RequestSpecificValues.Current_User.Get_Setting(thisSettingKey, "false");
                        if (String.Compare(enabled, "true", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // Get this file name
                            string file = thisSettingKey.Replace("TEI.MAPPING.", "");

                            // Also verify this mapping file exists
                            string filepath = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins", "tei", "mapping", file + ".xml");
                            if (!File.Exists(filepath))
                                continue;

                            // Since this exists, add to the mapping file list
                            mapping_files.Add(file);
                        }
                    }
                }

                // Show an error message if no mapping file exists
                if (mapping_files.Count == 0)
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em;\">You are not approved for any TEI mapping file.  Please let your system administrator know so they can approve you for an existing TEI mapping file.</td>");
                    Output.WriteLine("  </tr>");
                }
                else
                {

                    Output.WriteLine("  <tr>");
                    if (mapping_files.Count == 1)
                        Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-style:italic; color:#333; font-size:0.9em;\">The mapping file below will read the header information from your TEI file into the system, to facilitate searching and discovery of this resource.</td>");
                    else
                        Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-style:italic; color:#333; font-size:0.9em;\">Select the metadata mapping file below.  This mapping file will read the header information from your TEI file into the system, to facilitate searching and discovery of this resource.</td>");

                    Output.WriteLine("  </tr>");

                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td style=\"width:15px\" > &nbsp;</td>");
                    Output.WriteLine("    <td class=\"metadata_label\">Metadata Mapping:</a></td>");

                    // If they are approved for only one mapping file, just show that one as text, not a select box
                    if (mapping_files.Count == 1)
                    {
                        Output.WriteLine("    <td>");
                        Output.WriteLine("      " + mapping_files[0]);
                        Output.WriteLine("      <input type=\"hidden\" id=\"mapping_select\" name=\"mapping_select\" value=\"" + mapping_files[0] + "\" />");
                        Output.WriteLine("    </td>");
                    }
                    else
                    {

                        Output.WriteLine("    <td>");
                        Output.WriteLine("      <table>");
                        Output.WriteLine("        <tr>");
                        Output.WriteLine("          <td>");
                        Output.WriteLine("            <div id=\"mapping_div\">");
                        Output.WriteLine("              <select class=\"type_select\" name=\"mapping_select\" id=\"mapping_select\" >");

                        foreach (string file in mapping_files)
                        {
                            // Add this mapping information
                            if (String.Compare(file, mapping_file, StringComparison.OrdinalIgnoreCase) == 0)
                                Output.WriteLine("              <option value=\"" + file + "\" selected=\"selected\">" + file + "</option>");
                            else
                                Output.WriteLine("              <option value=\"" + file + "\">" + file + "</option>");
                        }

                        Output.WriteLine("              </select>");
                        Output.WriteLine("            </div>");
                        Output.WriteLine("          </td>");

                        //Output.WriteLine("          <td style=\"vertical-align:bottom\">");
                        //Output.WriteLine("            <a target=\"_TYPE\"  title=\"Get help.\" href=\"http://sobekrepository.org/help/typesimple\"><img class=\"help_button\" src=\"http://cdn.sobekrepository.org/images/misc/help_button.jpg\" /></a>");
                        //Output.WriteLine("          </td>");

                        Output.WriteLine("        </tr>");
                        Output.WriteLine("      </table>");
                        Output.WriteLine("    </td>");
                    }
                    Output.WriteLine("  </tr>");
                }

                Output.WriteLine("  <tr>");
                Output.WriteLine("    <td colspan=\"3\" class=\"sbkMySobek_TemplateTblTitle\" style=\"padding-top:25px\">Display Parameters (XSLT and CSS)</td>");
                Output.WriteLine("  </tr>");

                // Get the list of XSLT files that exist and this user is enabled for
                List<string> xslt_files = new List<string>();
                foreach (string thisSettingKey in RequestSpecificValues.Current_User.Settings.Keys)
                {
                    if (thisSettingKey.IndexOf("TEI.XSLT.") == 0)
                    {
                        // Only show enabled options
                        string enabled = RequestSpecificValues.Current_User.Get_Setting(thisSettingKey, "false");
                        if (String.Compare(enabled, "true", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // Get this file name
                            string file = thisSettingKey.Replace("TEI.XSLT.", "");

                            // Also verify this mapping file exists
                            string filepath = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins", "tei", "xslt", file);
                            if ((!File.Exists(filepath + ".xslt")) && (!File.Exists(filepath + ".xsl")))
                                continue;

                            // Since this exists, add to the xslt file list
                            xslt_files.Add(file);
                        }
                    }
                }

                // Show an error message if no XSLT file exists
                if (xslt_files.Count == 0)
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em;\">You are not approved for any TEI XSLT file.  Please let your system administrator know so they can approve you for an existing TEI XSLT file.</td>");
                    Output.WriteLine("  </tr>");
                }
                else
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-style:italic; color:#333; font-size:0.9em;\">The values below determine how the TEI will display within this system.  The XSLT will transform your TEI into HTML for display and the CSS file can add additional style to the resulting display.</td>");
                    Output.WriteLine("  </tr>");

                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td style=\"width:15px\" > &nbsp;</td>");
                    Output.WriteLine("    <td class=\"metadata_label\">XSLT File:</a></td>");

                    // If they are approved for only one XSLT file, just show that one as text, not a select box
                    if (xslt_files.Count == 1)
                    {
                        Output.WriteLine("    <td>");
                        Output.WriteLine("      " + xslt_files[0]);
                        Output.WriteLine("      <input type=\"hidden\" id=\"xslt_select\" name=\"xslt_select\" value=\"" + xslt_files[0] + "\" />");
                        Output.WriteLine("    </td>");
                    }
                    else
                    {

                        Output.WriteLine("    <td>");
                        Output.WriteLine("      <table>");
                        Output.WriteLine("        <tr>");
                        Output.WriteLine("          <td>");
                        Output.WriteLine("            <div id=\"xslt_div\">");
                        Output.WriteLine("              <select class=\"type_select\" name=\"xslt_select\" id=\"xslt_select\" >");

                        foreach (string file in xslt_files)
                        {

                            // Add this XSLT option
                            if (String.Compare(file, xslt_file, StringComparison.OrdinalIgnoreCase) == 0)
                                Output.WriteLine("              <option value=\"" + file + "\" selected=\"selected\">" + file + "</option>");
                            else
                                Output.WriteLine("              <option value=\"" + file + "\">" + file + "</option>");
                        }

                        Output.WriteLine("              </select>");
                        Output.WriteLine("            </div>");
                        Output.WriteLine("          </td>");

                        //Output.WriteLine("          <td style=\"vertical-align:bottom\">");
                        //Output.WriteLine("            <a target=\"_TYPE\"  title=\"Get help.\" href=\"http://sobekrepository.org/help/typesimple\"><img class=\"help_button\" src=\"http://cdn.sobekrepository.org/images/misc/help_button.jpg\" /></a>");
                        //Output.WriteLine("          </td>");

                        Output.WriteLine("        </tr>");
                        Output.WriteLine("      </table>");
                        Output.WriteLine("    </td>");
                    }
                    Output.WriteLine("  </tr>");
                }

                // CSS is not required, so check to see if any enable CSS's exist
                List<string> css_files = new List<string>();
                foreach (string thisSettingKey in RequestSpecificValues.Current_User.Settings.Keys)
                {
                    if (thisSettingKey.IndexOf("TEI.CSS.") == 0)
                    {
                        // Only show enabled options
                        string enabled = RequestSpecificValues.Current_User.Get_Setting(thisSettingKey, "false");
                        if (String.Compare(enabled, "true", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // Get this file name
                            string file = thisSettingKey.Replace("TEI.CSS.", "");

                            // Also verify this mapping file exists
                            string filepath = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins", "tei", "css", file + ".css");
                            if (!File.Exists(filepath))
                                continue;

                            // Since this exists, add to the css file list
                            css_files.Add(file);
                         }
                    }
                }

                // Only show the CSS options, if there are CSS options
                if (css_files.Count > 0)
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td style=\"width:15px\" > &nbsp;</td>");
                    Output.WriteLine("    <td class=\"metadata_label\">CSS File:</a></td>");

                    Output.WriteLine("    <td>");
                    Output.WriteLine("      <table>");
                    Output.WriteLine("        <tr>");
                    Output.WriteLine("          <td>");
                    Output.WriteLine("            <div id=\"css_div\">");
                    Output.WriteLine("              <select class=\"type_select\" name=\"css_select\" id=\"css_select\" >");
                    Output.WriteLine("                <option value=\"\">(none)</option>");
                    foreach (string file in css_files)
                    {
                        if (String.Compare(file, css_file, StringComparison.OrdinalIgnoreCase) == 0)
                            Output.WriteLine("                <option value=\"" + file + "\" selected=\"selected\">" + file + "</option>");
                        else
                            Output.WriteLine("                <option value=\"" + file + "\">" + file + "</option>");
                    }

                    Output.WriteLine("              </select>");
                    Output.WriteLine("            </div>");
                    Output.WriteLine("          </td>");

                    //Output.WriteLine("          <td style=\"vertical-align:bottom\">");
                    //Output.WriteLine("            <a target=\"_TYPE\"  title=\"Get help.\" href=\"http://sobekrepository.org/help/typesimple\"><img class=\"help_button\" src=\"http://cdn.sobekrepository.org/images/misc/help_button.jpg\" /></a>");
                    //Output.WriteLine("          </td>");

                    Output.WriteLine("        </tr>");
                    Output.WriteLine("      </table>");
                    Output.WriteLine("    </td>");

                    Output.WriteLine("  </tr>");
                }
                Output.WriteLine("</table>");

                // Add the bottom buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(2);\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(4);\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");

                Output.WriteLine("<br /><br /><br />");

                Output.WriteLine("</div>");
            }

            #endregion

            #region Add the metadata preview for this item

            if (currentProcessStep == 4)
            {
                // Get the mapping file
                string complete_mapping_file = Path.Combine(UI.UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins\\tei\\mapping", mapping_file + ".xml");
                string complete_tei_file = Path.Combine(userInProcessDirectory, tei_file);
                bool error = false;

                try
                {
                    // Create a new item again
                    new_item(RequestSpecificValues.Tracer);

                    // Use the mapper and pull the results
                    GenericXmlReader testMapper = new GenericXmlReader();
                    GenericXmlReaderResults returnValue = testMapper.ProcessFile(complete_tei_file, complete_mapping_file);

                    // Was there an error converting using the selected mapping?
                    if ((returnValue == null) || (!String.IsNullOrEmpty(returnValue.ErrorMessage)))
                    {
                        error = true;
                        if (returnValue != null)
                            error_message = "Error mapping the TEI XML file into the SobekCM item.<br /><br />" + returnValue.ErrorMessage + "<br /><br />Try a different mapping or contact your system administrator.<br /><br />";
                        else
                            error_message = "Error mapping the TEI XML file into the SobekCM item.<br /><br />Try a different mapping or contact your system administrator.<br /><br />";
                    }
                    else
                    {
                        // Create the mapper to map these values into the SobekCM object
                        Standard_Bibliographic_Mapper mappingObject = new Standard_Bibliographic_Mapper();

                        // Add all this information
                        foreach (MappedValue mappedValue in returnValue.MappedValues)
                        {
                            // If NONE mapping, just go on
                            if ((String.IsNullOrEmpty(mappedValue.Mapping)) || (String.Compare(mappedValue.Mapping, "None", StringComparison.OrdinalIgnoreCase) == 0))
                                continue;

                            if (!String.IsNullOrEmpty(mappedValue.Value))
                            {
                                // One mappig that is NOT bibliographic in nature is the full text
                                if ((String.Compare(mappedValue.Mapping, "FullText", StringComparison.OrdinalIgnoreCase) == 0) ||
                                    (String.Compare(mappedValue.Mapping, "Text", StringComparison.OrdinalIgnoreCase) == 0) ||
                                    (String.Compare(mappedValue.Mapping, "Full Text", StringComparison.OrdinalIgnoreCase) == 0))
                                {
                                    // Ensure no other TEXT file exists here ( in case a different file was uploaded )
                                    try
                                    {
                                        string text_file = Path.Combine(userInProcessDirectory, "fulltext.txt");
                                        StreamWriter writer = new StreamWriter(text_file);
                                        writer.Write(mappedValue.Value);
                                        writer.Flush();
                                        writer.Close();
                                    }
                                    catch
                                    {

                                    }
                                }
                                else
                                {
                                    mappingObject.Add_Data(item, mappedValue.Value, mappedValue.Mapping);
                                }
                            }
                        }

                        item.Save_METS();
                        HttpContext.Current.Session["Item"] = item;
                    }

                }
                catch (Exception ee)
                {
                    error_message = ee.Message;
                }

                Output.WriteLine("<div class=\"sbkMySobek_HomeText\" >");
                Output.WriteLine("<br />");

                Output.WriteLine("<h2>Step 4 of " + totalTemplatePages + ": Metadata Preview</h2>");

                // Was there a basic XML validation error?
                if ((error) && (!String.IsNullOrEmpty(error_message)))
                {
                    Output.WriteLine("<div style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em;\">");
                    Output.WriteLine(error_message);
                    Output.WriteLine("</div>");
                }

                Output.WriteLine("<blockquote>Below is a preview of the metadata extracted from your TEI file.<br /><br />");

                string citation = Standard_Citation_String(false, Tracer);
                Output.WriteLine(citation);

                // Add the bottom buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(3);\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");

                if ( !error )
                    Output.WriteLine("        <button onclick=\"return new_item_next_phase(5);\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");

                Output.WriteLine("      </div>");

                Output.WriteLine("</blockquote><br />");

                Output.WriteLine("<br />");
                Output.WriteLine("</div>");
            }

            #endregion

            #region Add the CompleteTemplate and surrounding HTML for the CompleteTemplate page step(s)

            if ((currentProcessStep >= 5) && (currentProcessStep <= (completeTemplate.InputPages_Count + 4)))
            {
                Output.WriteLine("<script type=\"text/javascript\" src=\"" + Static_Resources_Gateway.Jquery_Ui_1_10_3_Custom_Js + "\"></script>");

                Output.WriteLine("<div class=\"sbkMySobek_HomeText\">");
                Output.WriteLine("<br />");
                string template_page_title = completeTemplate.InputPages[currentProcessStep - 5].Title;
                if (template_page_title.Length == 0)
                    template_page_title = "Additional Item Description";
                string template_page_instructions = completeTemplate.InputPages[currentProcessStep - 5].Instructions;
                if (template_page_instructions.Length == 0)
                    template_page_instructions = "Enter additional basic information for your new item.";

                // Get the adjusted process step number ( for skipping permissions, usual step1 )
                int adjusted_process_step = currentProcessStep;
                if (completeTemplate.Permissions_Agreement.Length == 0)
                    adjusted_process_step--;

                Output.WriteLine("<h2>Step " + adjusted_process_step + " of " + totalTemplatePages + ": " + template_page_title + "</h2>");
                Output.WriteLine("<blockquote>" + template_page_instructions + "</blockquote>");
                if ((validationErrors != null) && (validationErrors.Count > 0) && (item.Web.Show_Validation_Errors))
                {
                    Output.WriteLine("<span style=\"color: red;\"><b>The following errors were detected:</b>");
                    Output.WriteLine("<blockquote>");
                    foreach (string validation_error in validationErrors)
                    {
                        Output.WriteLine(validation_error + "<br />");
                    }
                    Output.WriteLine("</blockquote>");
                    Output.WriteLine("</span>");
                    Output.WriteLine("<br />");
                    Output.WriteLine();
                }

                int next_step = currentProcessStep + 1;
                if (currentProcessStep == completeTemplate.InputPages_Count + 4)
                {
                    next_step = completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.None ? 9 : 8;
                }
                Output.WriteLine("<div id=\"tabContainer\" class=\"fulltabs\">");
                Output.WriteLine("  <div class=\"graytabscontent\">");
                Output.WriteLine("    <div class=\"tabpage\" id=\"tabpage_1\">");

                // Add the top buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + (currentProcessStep - 1) + ");\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + next_step + ");\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");
                Output.WriteLine("      <br /><br />");
                Output.WriteLine();

                bool isMozilla = ((!String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.Browser_Type)) && (RequestSpecificValues.Current_Mode.Browser_Type.ToUpper().IndexOf("FIREFOX") >= 0));

                string popup_forms = completeTemplate.Render_Template_HTML(Output, item, RequestSpecificValues.Current_Mode.Skin, isMozilla, RequestSpecificValues.Current_User, RequestSpecificValues.Current_Mode.Language, UI_ApplicationCache_Gateway.Translation, RequestSpecificValues.Current_Mode.Base_URL, currentProcessStep - 4);

                // Add the bottom buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + (currentProcessStep - 1) + ");\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + next_step + ");\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");
                Output.WriteLine("      <br />");
                Output.WriteLine();

                Output.WriteLine("    </div>");
                Output.WriteLine("  </div>");
                Output.WriteLine("</div>");
                Output.WriteLine("<br /><br />");

                if (popup_forms.Length > 0)
                    Output.WriteLine(popup_forms);

                Output.WriteLine("</div>");
            }

            #endregion

            if (currentProcessStep == 2)
            {

                Output.WriteLine("<div class=\"sbkMySobek_FileRightButtons\">");
                Output.WriteLine("      <button onclick=\"return new_upload_next_phase(1);\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("      <button onclick=\"return new_upload_next_phase(3);\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      <div id=\"circular_progress\" name=\"circular_progress\" class=\"hidden_progress\">&nbsp;</div>");
                Output.WriteLine("</div>");

                Output.WriteLine("<br /><br /><br />");
                Output.WriteLine("</div>");
                Output.WriteLine();
            }

            #region Add the list of all existing files and the URL box for the upload file/enter URL step

            if (currentProcessStep == 8)
            {
                if ((completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.File) || (completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.File_or_URL))
                {
                    string[] all_files = Directory.GetFiles(userInProcessDirectory);
                    SortedList<string, List<string>> image_files = new SortedList<string, List<string>>();
                    SortedList<string, List<string>> download_files = new SortedList<string, List<string>>();
                    foreach (string thisFile in all_files)
                    {
                        FileInfo thisFileInfo = new FileInfo(thisFile);

                        if ((thisFileInfo.Name.IndexOf("agreement.txt") != 0) && (thisFileInfo.Name.IndexOf("TEMP000001_00001.mets") != 0) && (thisFileInfo.Name.IndexOf("doc.xml") != 0) && (thisFileInfo.Name.IndexOf("sobek_mets.xml") != 0) && (thisFileInfo.Name.IndexOf("marc.xml") != 0))
                        {
                            // Get information about this files name and extension
                            string extension_upper = thisFileInfo.Extension.ToUpper();
                            string filename_sans_extension = thisFileInfo.Name.Replace(thisFileInfo.Extension, "");
                            string name_upper = thisFileInfo.Name.ToUpper();

                            // Is this a page image?
                            if ((extension_upper == ".JPG") || (extension_upper == ".TIF") || (extension_upper == ".JP2") || (extension_upper == ".JPX"))
                            {
                                // Exclude .QC.jpg files
                                if (name_upper.IndexOf(".QC.JPG") < 0)
                                {
                                    // If this is a thumbnail, trim off the THM part on the file name
                                    if (name_upper.IndexOf("THM.JPG") > 0)
                                    {
                                        filename_sans_extension = filename_sans_extension.Substring(0, filename_sans_extension.Length - 3);
                                    }

                                    // Is this the first image file with this name?
                                    if (image_files.ContainsKey(filename_sans_extension.ToLower()))
                                    {
                                        image_files[filename_sans_extension.ToLower()].Add(thisFileInfo.Name);
                                    }
                                    else
                                    {
                                        List<string> newImageGrouping = new List<string> { thisFileInfo.Name };
                                        image_files[filename_sans_extension.ToLower()] = newImageGrouping;
                                    }
                                }
                            }
                            else
                            {
                                // If this does not match the exclusion regular expression, than add this
                                if (!Regex.Match(thisFileInfo.Name, UI_ApplicationCache_Gateway.Settings.Resources.Files_To_Exclude_From_Downloads, RegexOptions.IgnoreCase).Success)
                                {
                                    if ((thisFileInfo.Name.IndexOf("marc.xml", StringComparison.OrdinalIgnoreCase) != 0) && (thisFileInfo.Name.IndexOf("marc.xml", StringComparison.OrdinalIgnoreCase) != 0) && (thisFileInfo.Name.IndexOf(".mets", StringComparison.OrdinalIgnoreCase) < 0))
                                    {
                                        // Is this the first image file with this name?
                                        if (download_files.ContainsKey(filename_sans_extension.ToLower()))
                                        {
                                            download_files[filename_sans_extension.ToLower()].Add(thisFileInfo.Name);
                                        }
                                        else
                                        {
                                            List<string> newDownloadGrouping = new List<string> { thisFileInfo.Name };
                                            download_files[filename_sans_extension.ToLower()] = newDownloadGrouping;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Any page images?
                    int file_counter = 0;
                    if (image_files.Count > 0)
                    {
                        Output.WriteLine("The following page images are already uploaded for this package:");
                        Output.WriteLine("<table class=\"sbkMySobek_FileTable\">");
                        Output.WriteLine("  <tr>");
                        Output.WriteLine("    <th style=\"width:350px;\">FILENAME</th>");
                        Output.WriteLine("    <th style=\"width:90px;\">SIZE</th>");
                        Output.WriteLine("    <th style=\"width:170px;\">DATE UPLOADED</th>");
                        Output.WriteLine("    <th style=\"width:90px;text-align:center;\">ACTION</th>");
                        Output.WriteLine("  </tr>");

                        int totalFileCount = 0;

                        //Determine the total number of files
                        foreach (string fileKey in image_files.Keys)
                        {
                            // Get this group of files
                            List<string> fileGroup = image_files[fileKey];
                            totalFileCount += fileGroup.Count();
                        }

                        // Step through all the page image file groups
                        foreach (string fileKey in image_files.Keys)
                        {
                            // Get this group of files
                            List<string> fileGroup = image_files[fileKey];

                            // Add each individual file
                            foreach (string thisFile in fileGroup)
                            {
                                file_counter++;

                                // Add the file name literal
                                FileInfo fileInfo = new FileInfo(userInProcessDirectory + "\\" + thisFile);
                                Output.WriteLine("  <tr style=\"min-height:22px\">");
                                Output.WriteLine("    <td>" + fileInfo.Name + "</td>");
                                if (fileInfo.Length < 1024)
                                    Output.WriteLine("    <td>" + fileInfo.Length + "</td>");
                                else
                                {
                                    if (fileInfo.Length < (1024 * 1024))
                                        Output.WriteLine("    <td>" + (fileInfo.Length / 1024) + " KB</td>");
                                    else
                                        Output.WriteLine("    <td>" + (fileInfo.Length / (1024 * 1024)) + " MB</td>");
                                }

                                Output.WriteLine("    <td>" + fileInfo.LastWriteTime + "</td>");

                                //add by Keven:replace single & double quote with ascII characters
                                string strFileName = fileInfo.Name;
                                if (strFileName.Contains("'") || strFileName.Contains("\""))
                                {
                                    strFileName = strFileName.Replace("'", "\\&#39;");
                                    strFileName = strFileName.Replace("\"", "\\&#34;");
                                }
                                Output.WriteLine("    <td style=\"text-align:center\"> <span class=\"sbkMySobek_ActionLink\">( <a href=\"\" onclick=\"return file_delete('" + strFileName + "');\">delete</a> )</span></td>");

                                Output.WriteLine("  </tr>");
                            }

                            // Now add the row to include the label
                            string input_name = "upload_label" + file_counter.ToString();
                            Output.WriteLine("  <tr style=\"min-height: 30px;\">");
                            Output.WriteLine("    <td colspan=\"4\">");
                            Output.WriteLine("      <div style=\"padding-left: 90px;\">");
                            Output.WriteLine("        <span style=\"color:gray\">Label:</span>");
                            Output.WriteLine("        <input type=\"hidden\" id=\"upload_file" + file_counter.ToString() + "\" name=\"upload_file" + file_counter.ToString() + "\" value=\"" + fileKey + "\" />");
                            if (HttpContext.Current.Session["file_" + fileKey] == null)
                            {
                                Output.WriteLine("      <input type=\"text\" class=\"sbkNgi_UploadFileLabel sbk_Focusable\" id=\"" + input_name + "\" name=\"" + input_name + "\" value=\"\" onchange=\"upload_label_fieldChanged(this.id," + totalFileCount + ");\"></input>");
                            }
                            else
                            {
                                string label_from_session = HttpContext.Current.Session["file_" + fileKey].ToString();
                                Output.WriteLine("      <input type=\"text\" class=\"sbkNgi_UploadFileLabel sbk_Focusable\" id=\"" + input_name + "\" name=\"" + input_name + "\" value=\"" + label_from_session + "\" onchange=\"upload_label_fieldChanged(this.id," + totalFileCount + ");\"></input>");
                            }
                            Output.WriteLine("      </div>");
                            Output.WriteLine("    </td>");
                            Output.WriteLine("  </tr>");
                            Output.WriteLine("  <tr><td class=\"sbkMySobek_FileTableRule\" colspan=\"4\"></td></tr>");
                        }
                        Output.WriteLine("</table>");
                    }

                    // Any download files?
                    if (download_files.Count > 0)
                    {
                        Output.WriteLine("The following files are already uploaded for this package and will be included as downloads:");
                        Output.WriteLine("<table class=\"sbkMySobek_FileTable\">");
                        Output.WriteLine("  <tr>");
                        Output.WriteLine("    <th style=\"width:350px;\">FILENAME</th>");
                        Output.WriteLine("    <th style=\"width:90px;\">SIZE</th>");
                        Output.WriteLine("    <th style=\"width:170px;\">DATE UPLOADED</th>");
                        Output.WriteLine("    <th style=\"width:90px;text-align:center;\">ACTION</th>");
                        Output.WriteLine("  </tr>");

                        int totalFileCount = 0;

                        //Determine the total number of files
                        foreach (string fileKey in download_files.Keys)
                        {
                            // Get this group of files
                            List<string> fileGroup = download_files[fileKey];
                            totalFileCount += fileGroup.Count();
                        }

                        // Step through all the download file groups
                        foreach (string fileKey in download_files.Keys)
                        {
                            // Get this group of files
                            List<string> fileGroup = download_files[fileKey];

                            // Add each individual file
                            foreach (string thisFile in fileGroup)
                            {
                                file_counter++;

                                // Add the file name literal
                                FileInfo fileInfo = new FileInfo(userInProcessDirectory + "\\" + thisFile);
                                Output.WriteLine("  <tr>");
                                Output.WriteLine("    <td>" + fileInfo.Name + "</td>");
                                if (fileInfo.Length < 1024)
                                    Output.WriteLine("    <td>" + fileInfo.Length + "</td>");
                                else
                                {
                                    if (fileInfo.Length < (1024 * 1024))
                                        Output.WriteLine("    <td>" + (fileInfo.Length / 1024) + " KB</td>");
                                    else
                                        Output.WriteLine("    <td>" + (fileInfo.Length / (1024 * 1024)) + " MB</td>");
                                }

                                Output.WriteLine("    <td>" + fileInfo.LastWriteTime + "</td>");

                                //add by Keven:replace single & double quote with ascII characters
                                string strFileName = fileInfo.Name;
                                if (strFileName.Contains("'") || strFileName.Contains("\""))
                                {
                                    strFileName = strFileName.Replace("'", "\\&#39;");
                                    strFileName = strFileName.Replace("\"", "\\&#34;");
                                }
                                Output.WriteLine("    <td style=\"text-align:center\"> <span class=\"sbkMySobek_ActionLink\">( <a href=\"\" onclick=\"return file_delete('" + strFileName + "');\">delete</a> )</span></td>");

                                Output.WriteLine("  </tr>");
                            }

                            // Now add the row to include the label
                            string input_name = "upload_label" + file_counter.ToString();
                            Output.WriteLine("  <tr>");
                            Output.WriteLine("    <td style=\"text-align:right; color:gray;\">Label:</td>");
                            Output.WriteLine("    <td colspan=\"4\">");
                            Output.WriteLine("      <input type=\"hidden\" id=\"upload_file" + file_counter.ToString() + "\" name=\"upload_file" + file_counter.ToString() + "\" value=\"" + fileKey + "\" />");
                            if (HttpContext.Current.Session["file_" + fileKey] == null)
                            {
                                Output.WriteLine("      <input type=\"text\" class=\"sbkNgi_UploadFileLabel sbk_Focusable\" id=\"" + input_name + "\" name=\"" + input_name + "\" onchange=\"upload_label_fieldChanged(this.id," + totalFileCount + ");\"></input>");
                            }
                            else
                            {
                                string label_from_session = HttpContext.Current.Session["file_" + fileKey].ToString();
                                Output.WriteLine("      <input type=\"text\" class=\"sbkNgi_UploadFileLabel sbk_Focusable\" id=\"" + input_name + "\" name=\"" + input_name + "\" value=\"" + label_from_session + "\" onchange=\"upload_label_fieldChanged(this.id," + totalFileCount + ");\"></input>");
                            }
                            Output.WriteLine("    </td>");
                            Output.WriteLine("  </tr>");
                            Output.WriteLine("  <tr><td class=\"sbkMySobek_FileTableRule\" colspan=\"4\"></td></tr>");
                        }
                        Output.WriteLine("</table>");
                    }
                }

                if ((completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.File_or_URL) || (completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.URL))
                {
                    Output.WriteLine("Enter a URL for this digital resource:");
                    Output.WriteLine("<blockquote>");
                    Output.WriteLine("<input type=\"text\" class=\"upload_url_input\" id=\"url_input\" name=\"url_input\" value=\"" + HttpUtility.HtmlEncode(item.Bib_Info.Location.Other_URL) + "\" ></input>");
                    Output.WriteLine("</blockquote>");
                }

                string completion_message;
                switch (completeTemplate.Upload_Types)
                {
                    case CompleteTemplate.Template_Upload_Types.URL:
                        completion_message = "Once the URL is entered, press SUBMIT to finish this item.";
                        break;

                    case CompleteTemplate.Template_Upload_Types.File_or_URL:
                        completion_message = "Once you enter any files and/or URL, press SUBMIT to finish this item.";
                        break;

                    case CompleteTemplate.Template_Upload_Types.File:
                        completion_message = "Once all files are uploaded, press SUBMIT to finish this item.";
                        break;

                    default:
                        completion_message = "Once complete, press SUBMIT to finish this item.";
                        break;
                }

                Output.WriteLine("<div class=\"sbkMySobek_FileRightButtons\">");
                Output.WriteLine("      <button onclick=\"return new_upload_next_phase(" + (completeTemplate.InputPages.Count + 4) + ");\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("      <button onclick=\"return new_upload_next_phase(9);\" class=\"sbkMySobek_BigButton\"> SUBMIT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      <div id=\"circular_progress\" name=\"circular_progress\" class=\"hidden_progress\">&nbsp;</div>");
                Output.WriteLine("</div>");
                Output.WriteLine();

                Output.WriteLine("<div class=\"sbkMySobek_FileCompletionMsg\">" + completion_message + "</div>");
                Output.WriteLine();
                Output.WriteLine("<br />");
                Output.WriteLine("</div>");
            }

            #endregion

            if (currentProcessStep == 9)
            {
                add_congratulations_html(Output, Tracer);
            }
        }
        /// <summary> This is an opportunity to write HTML directly into the main form, without
        /// using the pop-up html form architecture </summary>
        /// <param name="Output"> Textwriter to write the pop-up form HTML for this viewer </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        /// <remarks> This text will appear within the ItemNavForm form tags </remarks>
        public override void Write_ItemNavForm_Closing(TextWriter Output, Custom_Tracer Tracer)
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("Edit_TEI_Item_MySobekViewer.Write_ItemNavForm_Closing", "");
            }

            // Add the hidden fields first
            Output.WriteLine("<!-- Hidden field is used for postbacks to indicate what to save and reset -->");
            Output.WriteLine("<input type=\"hidden\" id=\"action\" name=\"action\" value=\"\" />");
            Output.WriteLine("<input type=\"hidden\" id=\"phase\" name=\"phase\" value=\"\" />");
            Output.WriteLine("<script type=\"text/javascript\" src=\"" + Static_Resources_Gateway.Sobekcm_Metadata_Js + "\" ></script>");

            #region Add the HTML to select the mapping, css, and xslt

            if (currentProcessStep == 1)
            {
                Output.WriteLine("      <br />");
                Output.WriteLine("    </td>");
                Output.WriteLine("  </tr>");
                Output.WriteLine("  <tr>");
                Output.WriteLine("    <td colspan=\"3\" class=\"sbkMySobek_TemplateTblTitle_first\">Metadata Mapping</td>");
                Output.WriteLine("  </tr>");

                // Get the list of Mapping files that exist and this user is enabled for
                List<string> mapping_files = new List<string>();
                foreach (string thisSettingKey in RequestSpecificValues.Current_User.Settings.Keys)
                {
                    if (thisSettingKey.IndexOf("TEI.MAPPING.") == 0)
                    {
                        // Only show enabled options
                        string enabled = RequestSpecificValues.Current_User.Get_Setting(thisSettingKey, "false");
                        if (String.Compare(enabled, "true", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // Get this file name
                            string file = thisSettingKey.Replace("TEI.MAPPING.", "");

                            // Also verify this mapping file exists
                            string filepath = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins", "tei", "mapping", file + ".xml");
                            if (!File.Exists(filepath))
                                continue;

                            // Since this exists, add to the css file list
                            mapping_files.Add(file);
                        }
                    }
                }

                // Show an error message if no mapping file exists
                if (mapping_files.Count == 0)
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em;\">You are not approved for any TEI mapping file.  Please let your system administrator know so they can approve you for an existing TEI mapping file.</td>");
                    Output.WriteLine("  </tr>");
                }
                else
                {

                    Output.WriteLine("  <tr>");
                    if (mapping_files.Count == 1)
                        Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-style:italic; color:#333; font-size:0.9em;\">The mapping file below will read the header information from your TEI file into the system, to facilitate searching and discovery of this resource.</td>");
                    else
                        Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-style:italic; color:#333; font-size:0.9em;\">Select the metadata mapping file below.  This mapping file will read the header information from your TEI file into the system, to facilitate searching and discovery of this resource.</td>");
                    Output.WriteLine("  </tr>");

                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td style=\"width:15px\" > &nbsp;</td>");
                    Output.WriteLine("    <td class=\"metadata_label\">Metadata Mapping:</a></td>");

                    // If they are approved for only one mapping file, just show that one as text, not a select box
                    if (mapping_files.Count == 1)
                    {
                        Output.WriteLine("    <td>");
                        Output.WriteLine("      " + mapping_files[0]);
                        Output.WriteLine("      <input type=\"hidden\" id=\"mapping_select\" name=\"mapping_select\" value=\"" + mapping_files[0] + "\" />");
                        Output.WriteLine("    </td>");
                    }
                    else
                    {

                        Output.WriteLine("    <td>");
                        Output.WriteLine("      <table>");
                        Output.WriteLine("        <tr>");
                        Output.WriteLine("          <td>");
                        Output.WriteLine("            <div id=\"mapping_div\">");
                        Output.WriteLine("              <select class=\"type_select\" name=\"mapping_select\" id=\"mapping_select\" >");

                        foreach (string file in mapping_files)
                        {
                            // Add this mapping information
                            if (String.Compare(file, mapping_file, StringComparison.OrdinalIgnoreCase) == 0)
                                Output.WriteLine("              <option value=\"" + file + "\" selected=\"selected\">" + file + "</option>");
                            else
                                Output.WriteLine("              <option value=\"" + file + "\">" + file + "</option>");
                        }

                        Output.WriteLine("              </select>");
                        Output.WriteLine("            </div>");
                        Output.WriteLine("          </td>");

                        //Output.WriteLine("          <td style=\"vertical-align:bottom\">");
                        //Output.WriteLine("            <a target=\"_TYPE\"  title=\"Get help.\" href=\"http://sobekrepository.org/help/typesimple\"><img class=\"help_button\" src=\"http://cdn.sobekrepository.org/images/misc/help_button.jpg\" /></a>");
                        //Output.WriteLine("          </td>");

                        Output.WriteLine("        </tr>");
                        Output.WriteLine("      </table>");
                        Output.WriteLine("    </td>");
                    }
                    Output.WriteLine("  </tr>");
                }

                Output.WriteLine("  <tr>");
                Output.WriteLine("    <td colspan=\"3\" class=\"sbkMySobek_TemplateTblTitle\" style=\"padding-top:25px\">Display Parameters (XSLT and CSS)</td>");
                Output.WriteLine("  </tr>");

                // Get the list of XSLT files that exist and this user is enabled for
                List<string> xslt_files = new List<string>();
                foreach (string thisSettingKey in RequestSpecificValues.Current_User.Settings.Keys)
                {
                    if (thisSettingKey.IndexOf("TEI.XSLT.") == 0)
                    {
                        // Only show enabled options
                        string enabled = RequestSpecificValues.Current_User.Get_Setting(thisSettingKey, "false");
                        if (String.Compare(enabled, "true", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // Get this file name
                            string file = thisSettingKey.Replace("TEI.XSLT.", "");

                            // Also verify this mapping file exists
                            string filepath = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins", "tei", "xslt", file );
                            if ((!File.Exists(filepath + ".xslt")) && ( !File.Exists(filepath + ".xsl")))
                                continue;

                            // Since this exists, add to the xslt file list
                            xslt_files.Add(file);
                        }
                    }
                }

                // Show an error message if no XSLT file exists
                if (xslt_files.Count == 0)
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em;\">You are not approved for any TEI XSLT file.  Please let your system administrator know so they can approve you for an existing TEI XSLT file.</td>");
                    Output.WriteLine("  </tr>");
                }
                else
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td colspan=\"3\" style=\"padding-left:30px;font-style:italic; color:#333; font-size:0.9em;\">The values below determine how the TEI will display within this system.  The XSLT will transform your TEI into HTML for display and the CSS file can add additional style to the resulting display.</td>");
                    Output.WriteLine("  </tr>");

                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td style=\"width:15px\" > &nbsp;</td>");
                    Output.WriteLine("    <td class=\"metadata_label\">XSLT File:</a></td>");

                    // If they are approved for only one XSLT file, just show that one as text, not a select box
                    if (xslt_files.Count == 1)
                    {
                        Output.WriteLine("    <td>");
                        Output.WriteLine("      " + xslt_files[0]);
                        Output.WriteLine("      <input type=\"hidden\" id=\"xslt_select\" name=\"xslt_select\" value=\"" + xslt_files[0] + "\" />");
                        Output.WriteLine("    </td>");
                    }
                    else
                    {

                        Output.WriteLine("    <td>");
                        Output.WriteLine("      <table>");
                        Output.WriteLine("        <tr>");
                        Output.WriteLine("          <td>");
                        Output.WriteLine("            <div id=\"xslt_div\">");
                        Output.WriteLine("              <select class=\"type_select\" name=\"xslt_select\" id=\"xslt_select\" >");

                        foreach (string file in xslt_files)
                        {

                            // Add this XSLT option
                            if (String.Compare(file, xslt_file, StringComparison.OrdinalIgnoreCase) == 0)
                                Output.WriteLine("              <option value=\"" + file + "\" selected=\"selected\">" + file + "</option>");
                            else
                                Output.WriteLine("              <option value=\"" + file + "\">" + file + "</option>");
                        }

                        Output.WriteLine("              </select>");
                        Output.WriteLine("            </div>");
                        Output.WriteLine("          </td>");

                        //Output.WriteLine("          <td style=\"vertical-align:bottom\">");
                        //Output.WriteLine("            <a target=\"_TYPE\"  title=\"Get help.\" href=\"http://sobekrepository.org/help/typesimple\"><img class=\"help_button\" src=\"http://cdn.sobekrepository.org/images/misc/help_button.jpg\" /></a>");
                        //Output.WriteLine("          </td>");

                        Output.WriteLine("        </tr>");
                        Output.WriteLine("      </table>");
                        Output.WriteLine("    </td>");
                    }
                    Output.WriteLine("  </tr>");
                }

                // CSS is not required, so check to see if any enable CSS's exist
                List<string> css_files = new List<string>();
                foreach (string thisSettingKey in RequestSpecificValues.Current_User.Settings.Keys)
                {
                    if (thisSettingKey.IndexOf("TEI.CSS.") == 0)
                    {
                        // Only show enabled options
                        string enabled = RequestSpecificValues.Current_User.Get_Setting(thisSettingKey, "false");
                        if (String.Compare(enabled, "true", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // Get this file name
                            string file = thisSettingKey.Replace("TEI.CSS.", "");

                            // Also verify this mapping file exists
                            string filepath = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins", "tei", "css", file + ".css");
                            if (!File.Exists(filepath))
                                continue;

                            // Since this exists, add to the css file list
                            css_files.Add(file);
                        }
                    }
                }

                // Only show the CSS options, if there are CSS options
                if (css_files.Count > 0)
                {
                    Output.WriteLine("  <tr>");
                    Output.WriteLine("    <td style=\"width:15px\" > &nbsp;</td>");
                    Output.WriteLine("    <td class=\"metadata_label\">CSS File:</a></td>");

                    Output.WriteLine("    <td>");
                    Output.WriteLine("      <table>");
                    Output.WriteLine("        <tr>");
                    Output.WriteLine("          <td>");
                    Output.WriteLine("            <div id=\"css_div\">");
                    Output.WriteLine("              <select class=\"type_select\" name=\"css_select\" id=\"css_select\" >");
                    Output.WriteLine("                <option value=\"\">(none)</option>");
                    foreach (string file in css_files)
                    {
                        if (String.Compare(file, css_file, StringComparison.OrdinalIgnoreCase) == 0)
                            Output.WriteLine("                <option value=\"" + file + "\" selected=\"selected\">" + file + "</option>");
                        else
                            Output.WriteLine("                <option value=\"" + file + "\">" + file + "</option>");
                    }

                    Output.WriteLine("              </select>");
                    Output.WriteLine("            </div>");
                    Output.WriteLine("          </td>");

                    //Output.WriteLine("          <td style=\"vertical-align:bottom\">");
                    //Output.WriteLine("            <a target=\"_TYPE\"  title=\"Get help.\" href=\"http://sobekrepository.org/help/typesimple\"><img class=\"help_button\" src=\"http://cdn.sobekrepository.org/images/misc/help_button.jpg\" /></a>");
                    //Output.WriteLine("          </td>");

                    Output.WriteLine("        </tr>");
                    Output.WriteLine("      </table>");
                    Output.WriteLine("    </td>");

                    Output.WriteLine("  </tr>");
                }

                Output.WriteLine("</table>");

                // Add the bottom buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_cancel();\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> CANCEL </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(2);\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");

                Output.WriteLine("<br /><br /><br />");

                Output.WriteLine("</div>");
            }

            #endregion

            #region Add the HTML to allow the source of the TEI file to be edited

            // Add code to edit the TEI
            if (currentProcessStep == 2)
            {
                Output.WriteLine("<script src=\"" + Static_Resources_Gateway.Sobekcm_Metadata_Js + "\" type=\"text/javascript\"></script>");
                Output.WriteLine("<h2>Step 2 of " + totalTemplatePages + ": Edit TEI</h2>");

                // Was there a basic XML validation error?
                if (!String.IsNullOrEmpty(error_message))
                {
                    Output.WriteLine("<div style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em; padding-bottom: 20px;\">");
                    Output.WriteLine(error_message);
                    Output.WriteLine("</div>");
                }
                else if (!String.IsNullOrEmpty(success_message))
                {
                    Output.WriteLine("<div style=\"padding-left:30px;font-weight:bold; color:Blue; font-size:1.1em; padding-bottom: 20px;\">");
                    Output.WriteLine(success_message);
                    Output.WriteLine("</div>");
                }

                Output.WriteLine("</div>");

                // Find the TEI source file (may be newly uploaded file)
                string current_tei_file = SobekFileSystem.Resource_Network_Uri(bibid, vid, original_tei_file);
                if (!String.IsNullOrEmpty(new_tei_file))
                {
                    current_tei_file = Path.Combine(userInProcessDirectory, new_tei_file);
                }

                // Get the TEI source
                string tei_source_content = null;
                try
                {
                    tei_source_content = File.ReadAllText(current_tei_file);
                }
                catch (Exception)
                {
                    tei_source_content = "ERROR READING TEI SOURCE.  ( " + current_tei_file + " )";
                    throw;
                }

                // Add the ACE editor
                AceEditor editor = new AceEditor(AceEditor_Mode.XML)
                {
                    ContentsId = "tei_source_content",
                    EditorId = "sbkEtmv_TeiEditor",
                    BaseUrl = RequestSpecificValues.Current_Mode.Base_URL
                };
                editor.Add_To_Stream(Output, tei_source_content);

                // Add the bottom buttons
                Output.WriteLine("<div class=\"sbkMySobek_HomeText\">");
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_cancel();\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> CANCEL </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(2);\" class=\"sbkMySobek_BigButton\"> SAVE </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(3);\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");

                Output.WriteLine("<br /><br /><br />");

                Output.WriteLine("</div>");
            }

            #endregion

            #region Convert TEI to METS and add the metadata preview for this item

            if (currentProcessStep == 3)
            {
                // Get the mapping file
                string complete_mapping_file = Path.Combine(UI.UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins\\tei\\mapping", mapping_file + ".xml");
                string complete_tei_file = original_tei_file;
                if (!String.IsNullOrEmpty(new_tei_file))
                    complete_tei_file = Path.Combine(userInProcessDirectory, new_tei_file);
                bool error = false;

                try
                {
                    // Save some data
                    string holding_code = editingItem.Bib_Info.Location.Holding_Code;
                    string source_code = editingItem.Bib_Info.Source.Code;
                    TypeOfResource_SobekCM_Enum original_type = editingItem.Bib_Info.SobekCM_Type;
                    string original_title = editingItem.Bib_Info.Main_Title.Title;

                    // Clear the existing bibliographic information
                    editingItem.Bib_Info.Clear();

                    // Use the mapper and pull the results
                    GenericXmlReader testMapper = new GenericXmlReader();
                    GenericXmlReaderResults returnValue = testMapper.ProcessFile(complete_tei_file, complete_mapping_file);

                    // Was there an error converting using the selected mapping?
                    if ((returnValue == null) || (!String.IsNullOrEmpty(returnValue.ErrorMessage)))
                    {
                        error = true;
                        if (returnValue != null)
                            error_message = "Error mapping the TEI XML file into the SobekCM item.<br /><br />" + returnValue.ErrorMessage + "<br /><br />Try a different mapping or contact your system administrator.<br /><br />";
                        else
                            error_message = "Error mapping the TEI XML file into the SobekCM item.<br /><br />Try a different mapping or contact your system administrator.<br /><br />";
                    }
                    else
                    {
                        // Create the mapper to map these values into the SobekCM object
                        Standard_Bibliographic_Mapper mappingObject = new Standard_Bibliographic_Mapper();

                        // Add all this information
                        foreach (MappedValue mappedValue in returnValue.MappedValues)
                        {
                            // If NONE mapping, just go on
                            if ((String.IsNullOrEmpty(mappedValue.Mapping)) || (String.Compare(mappedValue.Mapping, "None", StringComparison.OrdinalIgnoreCase) == 0))
                                continue;

                            if (!String.IsNullOrEmpty(mappedValue.Value))
                            {
                                // One mappig that is NOT bibliographic in nature is the full text
                                if ((String.Compare(mappedValue.Mapping, "FullText", StringComparison.OrdinalIgnoreCase) == 0) ||
                                    (String.Compare(mappedValue.Mapping, "Text", StringComparison.OrdinalIgnoreCase) == 0) ||
                                    (String.Compare(mappedValue.Mapping, "Full Text", StringComparison.OrdinalIgnoreCase) == 0))
                                {
                                    // Ensure no other TEXT file exists here ( in case a different file was uploaded )
                                    try
                                    {
                                        string text_file = Path.Combine(userInProcessDirectory, "fulltext.txt");
                                        StreamWriter writer = new StreamWriter(text_file);
                                        writer.Write(mappedValue.Value);
                                        writer.Flush();
                                        writer.Close();
                                    }
                                    catch
                                    {

                                    }
                                }
                                else
                                {
                                    mappingObject.Add_Data(editingItem, mappedValue.Value, mappedValue.Mapping);
                                }
                            }
                        }

                        // If there is no title, assign a default
                        if (String.IsNullOrEmpty(editingItem.Bib_Info.Main_Title.Title))
                            editingItem.Bib_Info.Main_Title.Title = "TEI Item";

                        // Ensure source and holding codes remain
                        if (String.IsNullOrEmpty(editingItem.Bib_Info.Location.Holding_Code)) editingItem.Bib_Info.Location.Holding_Code = holding_code;
                        if (String.IsNullOrEmpty(editingItem.Bib_Info.Source.Code)) editingItem.Bib_Info.Source.Code = source_code;
                        if ( editingItem.Bib_Info.SobekCM_Type == TypeOfResource_SobekCM_Enum.UNKNOWN )
                            editingItem.Bib_Info.SobekCM_Type = original_type;
                        if (String.IsNullOrEmpty(editingItem.Bib_Info.Main_Title.Title))
                            editingItem.Bib_Info.Main_Title.Title = original_title;

                        editingItem.Save_METS();
                        HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] = editingItem;

                    }

                }
                catch (Exception ee)
                {
                    error_message = ee.Message;
                }

                // Save this as the editing item
                HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] = editingItem;

                Output.WriteLine("<div class=\"sbkMySobek_HomeText\" >");
                Output.WriteLine("<br />");

                Output.WriteLine("<h2>Step 3 of " + totalTemplatePages + ": Metadata Preview</h2>");

                // Was there a basic XML validation error?
                if ((error) && (!String.IsNullOrEmpty(error_message)))
                {
                    Output.WriteLine("<div style=\"padding-left:30px;font-weight:bold; color:Red; font-size:1.1em;\">");
                    Output.WriteLine(error_message);
                    Output.WriteLine("</div>");
                }

                Output.WriteLine("<blockquote>Below is a preview of the metadata extracted from your TEI file.<br /><br />");

                string citation = Standard_Citation_String(false, Tracer);
                Output.WriteLine(citation);

                // Add the bottom buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(2);\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");

                if (!error)
                    Output.WriteLine("        <button onclick=\"return new_item_next_phase(4);\" class=\"sbkMySobek_BigButton\"> NEXT <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");

                Output.WriteLine("      </div>");

                Output.WriteLine("</blockquote><br />");

                Output.WriteLine("<br />");
                Output.WriteLine("</div>");
            }

            #endregion

            #region Add the CompleteTemplate and surrounding HTML for the CompleteTemplate page step(s)

            if ((currentProcessStep >= 4) && (currentProcessStep <= (completeTemplate.InputPages_Count + 3)))
            {
                Output.WriteLine("<script type=\"text/javascript\" src=\"" + Static_Resources_Gateway.Jquery_Ui_1_10_3_Custom_Js + "\"></script>");

                Output.WriteLine("<div class=\"sbkMySobek_HomeText\">");
                Output.WriteLine("<br />");
                string template_page_title = completeTemplate.InputPages[currentProcessStep - 4].Title;
                if (template_page_title.Length == 0)
                    template_page_title = "Additional Item Description";
                string template_page_instructions = completeTemplate.InputPages[currentProcessStep - 4].Instructions;
                if (template_page_instructions.Length == 0)
                    template_page_instructions = "Enter additional basic information for your item.";

                // Get the adjusted process step number ( for skipping permissions, usual step1 )
                int adjusted_process_step = currentProcessStep;
                if (completeTemplate.Permissions_Agreement.Length == 0)
                    adjusted_process_step--;

                Output.WriteLine("<h2>Step " + adjusted_process_step + " of " + totalTemplatePages + ": " + template_page_title + "</h2>");
                Output.WriteLine("<blockquote>" + template_page_instructions + "</blockquote>");
                if ((validationErrors != null) && (validationErrors.Count > 0) && (item.Web.Show_Validation_Errors))
                {
                    Output.WriteLine("<span style=\"color: red;\"><b>The following errors were detected:</b>");
                    Output.WriteLine("<blockquote>");
                    foreach (string validation_error in validationErrors)
                    {
                        Output.WriteLine(validation_error + "<br />");
                    }
                    Output.WriteLine("</blockquote>");
                    Output.WriteLine("</span>");
                    Output.WriteLine("<br />");
                    Output.WriteLine();
                }

                int next_step = currentProcessStep + 1;
                if (currentProcessStep == completeTemplate.InputPages_Count + 3)
                {
                    next_step = 9;
                }
                Output.WriteLine("<div id=\"tabContainer\" class=\"fulltabs\">");
                Output.WriteLine("  <div class=\"graytabscontent\">");
                Output.WriteLine("    <div class=\"tabpage\" id=\"tabpage_1\">");

                string next_button_text = "NEXT";
                if (currentProcessStep <= (completeTemplate.InputPages_Count + 3))
                    next_button_text = "COMPLETE";

                // Add the top buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + (currentProcessStep - 1) + ");\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + next_step + ");\" class=\"sbkMySobek_BigButton\"> " + next_button_text + " <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");
                Output.WriteLine("      <br /><br />");
                Output.WriteLine();

                bool isMozilla = ((!String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.Browser_Type)) && (RequestSpecificValues.Current_Mode.Browser_Type.ToUpper().IndexOf("FIREFOX") >= 0));

                string popup_forms = completeTemplate.Render_Template_HTML(Output, editingItem, RequestSpecificValues.Current_Mode.Skin, isMozilla, RequestSpecificValues.Current_User, RequestSpecificValues.Current_Mode.Language, UI_ApplicationCache_Gateway.Translation, RequestSpecificValues.Current_Mode.Base_URL, currentProcessStep - 3);

                // Add the bottom buttons
                Output.WriteLine("      <div class=\"sbkMySobek_RightButtons\">");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + (currentProcessStep - 1) + ");\" class=\"sbkMySobek_BigButton\"><img src=\"" + Static_Resources_Gateway.Button_Previous_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_LeftImg\" alt=\"\" /> BACK </button> &nbsp; &nbsp; ");
                Output.WriteLine("        <button onclick=\"return new_item_next_phase(" + next_step + ");\" class=\"sbkMySobek_BigButton\"> " + next_button_text + " <img src=\"" + Static_Resources_Gateway.Button_Next_Arrow_Png + "\" class=\"sbkMySobek_RoundButton_RightImg\" alt=\"\" /></button>");
                Output.WriteLine("      </div>");
                Output.WriteLine("      <br />");
                Output.WriteLine();

                Output.WriteLine("    </div>");
                Output.WriteLine("  </div>");
                Output.WriteLine("</div>");
                Output.WriteLine("<br /><br />");

                if (popup_forms.Length > 0)
                    Output.WriteLine(popup_forms);

                Output.WriteLine("</div>");
            }

            #endregion

            Output.WriteLine("</div>");
            Output.WriteLine("</div>");
            Output.WriteLine("</div>");
        }