#Region "asp2dotnet converter header"
' File Protected: false
#End Region

Imports System.Data.SqlClient
Imports System.DirectoryServices

Public Class pageMessage

    Inherits AspPage

#Region "Global Variables"

    ' used to calculate and show page load times
    Public Property PageStartTime As Object

    ' (form_siteNum)
    Public Property Whatsite As Object

    ' (form_Location)
    Public Property Whatlocation As Object

    ' USER IP ADDRESS
    Public Property UserIP As Object

    ' USERNAME
    Public Property UserName As Object

    ' end if
    ' USER SID
    Public Property UserSID As Object

    ' = String = Hex value of Byte array of AD SID for username
    ' Application Variable caches the UserSID to prevent having to poll AD every page hit.
    ' The CheckAdmin() function will poll AD and verify it
    Private Property S As Object
    Private Property I As Object
    Private Property A As Object
    Private Property L As Object
    Public Property GLAST As Object
    Public Property GFIRST As Object
    Public Property GSSN As Object

    ' ---------------------------------------------------------------------------------
    ' ' Prediction order: 1 / 3
    Public Property SiteName As Object
    Public Property AdminAccess As Object
    Public Property AdminSite As Object
    Public Property AdminSites As Object
    Public Property AdminLocation As Object
    Public Property AdminTeam As Object
    Public Property AdminType As Object
    Public Property dTimezoneOffset As Double = ConfigurationManager.AppSettings("tzOffset")
#End Region

#Region "Used Modules"
    Private __Vb6 As Vb6 = Nothing
    Private ReadOnly Property _Vb6 As Vb6
        Get
            If __Vb6 Is Nothing Then
                __Vb6 = createInstance(GetType(Vb6))
            End If
            Return __Vb6
        End Get
    End Property
    Private __clsMessageVAR As clsMessageVAR = Nothing
    Private form_LocationIndex As Object
    Private form_TeamIndex As Object
    Private newName As Object
    Private oldIndex As String
    Private db As Object
    Private rs As Object
    Private EXTRAMSG As Object
    Private form_Access As String
    Private form_Error As String
    Private form_Active As Object
    Private form_AssignTo As String
    Private form_Transfer As String
    Private form_CheckDone As String
    Private form_CheckSuppressDetails As String
    Private form_ReturnCall As String
    Private form_Details As String
    Private form_Notes As String
    Private form_Email As String
    Private oldEmailAssign As Object
    Private form_EmailAssign As Object
    Private oldEmailNew As Object
    Private form_EmailNew As Object
    Private oldEmailStatus As Object
    Private form_EmailStatus As Object
    Private form_FlagOn As Object
    Private form_Username As String
    Private itemChanged As Boolean
    Private rsAssigned As String
    Private form_MemberIndex As String
    Private ADE As String
    Private ADFULL As Object
    Private ADF As String
    Private ADL As String
    Private ACACTION As String
    Private form_Method As String
    Private ADloop As String
    Private ADSID As String
    Private ADT As String
    Private ADU As String
    Private AssignedTo As String
    Private ADrows As String()
    Private strADResults As Object
    Private caLocationName As Object
    Private form_SiteNum As String
    Private form_Name As String
    Private form_ScriptIndex As String
    Private oldShowOn As Object
    Private form_ShowOn As Object
    Private form_SID As String
    Private form_SortOrder As String
    Private form_Waiting As String
    Private form_Status As String
    Private form_Title As String
    Private form_Type As String
    Private newSID As Object
    Private newSSI As Integer
    Private newTitle As String
    Private newUsername As String
    Private oldNotes As String
    Private newNotes As String
    Private oldSID As Object
    Private oldTeamIndex As Object
    Private oldTitle As String
    Private optionCount As Integer
    Private optionItem As String
    Private rsFirstName As Object
    Private rsLastName As Object
    Private rsLastFour As Object
    Private rsDateOfBirth As Object
    Private rsMedChoice As Object
    Private rsMedName As Object
    Private rsBestTime As Object
    Private rsPhone As Object
    Private rsReason As Object
    Private rsReturnCall As Object
    Private rsVendorTaxID As Object
    Private rsSiteNum As Object
    Private rsStatus As Object
    Private rsTeamIndex As Object
    Private rsVendorContactInfo As Object
    Private rsVendorName As Object
    Private ReasonRadio As String
    Private reasonrs As Object
    Private rsComment As String
    Private rsCompleted As String
    Private rsFullID As String
    Private rsLocationIndex As Object
    Private caTeamName As String
    Private safeAction As String
    Private safeValue As Object
    Private strAge As Double
    Private sSqlString As Object
    Private tempEmail As String
    Private tempNames As Object
    Private memoNotes As Object
    Private newActive As Object
    Private newEmail As Object
    Private newEmailAssign As Object
    Private newEmailNew As Object
    Private newEmailStatus As Object
    Private newShowOn As Object
    Private PurgeDatePII As Date
    Private MSGdelay As Object
    Private rs3 As Object
    Private rsDt As String
    Private rsEmailSent As String
    Private rsTm As Object
    Private rsUsername As Object
    Private MemberIndex As Integer
    Private MemberMax As Integer
    Private form_flagOther As String
    Private form_HoDate As String
    Private VHDate As Date
    Private theDate As Date = Date.Now.AddHours(dTimezoneOffset)
    Private Sc_LocationIndex As Object
    Private form_MemberIndexe As String
    Private bShowHelpMenu As Boolean = False

    Private ReadOnly Property _clsMessageVAR As clsMessageVAR
        Get
            If __clsMessageVAR Is Nothing Then
                __clsMessageVAR = createInstance(GetType(clsMessageVAR))
            End If
            Return __clsMessageVAR
        End Get
    End Property
#End Region


    '==================================== XSS/Injection Stop ===
    Function strip_tags(unsafeString)
        Dim regEx
        regEx = New Regex("(\<(/?[^\>]+)\>)")
        strip_tags = regEx.Replace(unsafeString, "")
        regEx = Nothing
    End Function

    ' kill sSqlString commands   //Be aware of user problems that might be cause by this.  I'm pretty sure
    Function killChars(strWords)
        Dim badChars
        Dim newChars
        Dim i
        badChars = New Object() {"select", " drop ", ";", "--", "insert", "delete", "xp_", " or ", " and ", " from ", " into ", "set ", "waitfor", "where ", "values", "null", "http", " js ", "declare", "script", "xp_", "CRLF", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "&quot;", "&amp;", "&lt;", "&gt;", "exec ", "onvarchar", "cast ", "00100111", "00100010", "00111100", "0x", "exe ", "go ", "create", "convert"}
        newChars = Me.strip_tags(strWords)
        For i = 0 To UBound(badChars)
            newChars = Replace(newChars, badChars(i), "")
        Next

        killChars = newChars
    End Function

    Function JustToTheFirstSpace(strIn)
        Dim toked
        strIn = Replace(strIn, "(", "|")
        strIn = Replace(strIn, "<", "|")
        strIn = Replace(strIn, ";", "|")
        strIn = Replace(strIn, "--", "|")
        strIn = Replace(strIn, "=", "|")
        strIn = Replace(strIn, """", "|")
        strIn = Replace(strIn, ">", "|")
        strIn = Replace(strIn, ")", "|")

        toked = Split(strIn, "|", -1, 1)
        If UBound(toked) > 0 Then
            JustToTheFirstSpace = toked(0)
        Else
            JustToTheFirstSpace = strIn
        End If
    End Function

    Sub Debug(scope)
        Dim tempSL
        ' used to display all variable values
        Response.Write("A=" & A & ".<br>")
        Response.Write("AdminAccess=" & AdminAccess & ".<br>")
        Response.Write("AdminSite=" & AdminSite & ".<br>")
        Response.Write("AdminLocation=" & AdminLocation & ".<br>")
        Response.Write("AdminTeam=" & AdminTeam & ".<br>")
        Response.Write("AdminType=" & AdminType & ".<br>")
        Response.Write("UserSID=" & UserSID & ".<br>")

        Response.Write("S=" & S & ".<br>")
        Response.Write("SiteName=" & SiteName & ".<br>")
        Response.Write("whatsite=" & Whatsite & ".<br>")
        Response.Write("whatlocation=" & Whatlocation & ".<br>")
        If scope <> "Local" Then
            Response.Write("SingleSite=" & SingleSite() & ".<br>")
            tempSL = Me.SingleLocation()
            Response.Write("SingleLocation=" & tempSL & ".<br>")
            '  SingleTeam takes tab_Locations.Lo_Index, not SiteNum
            '	Response.Write("SingleTeam=" & SingleTeam(whatsite) & ".<br>")
            Response.Write("SingleTeam=" & SingleTeam(tempSL) & ".<br>")
        End If

        Response.Write("Form(form_Phase)=" & Request.Form("form_Phase") & ".<br>")
        If (Not Request.QueryString("action") Is Nothing) Then Response.Write("QueryString(action)=" & Request.QueryString("action").ToString() & ".<br>")
        If (Not Request.QueryString("menu") Is Nothing) Then Response.Write("QueryString(menu)=" & Request.QueryString("menu").ToString() & ".<br>")
        Response.Write("I=" & I & ".<br>")
    End Sub

    Sub ErrorHandler(strError, bShow, bQuit)
        ' "strError": log the error message
        ' bShow: 
        '	if true, then show the error message and details to the screen
        '	if false, then suppress output
        ' bQuit:
        '   if true, then exit the ASP processing
        '   if false, then continue after error display

        If Response.Buffer = True And bShow = True Then
            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
            Response.Flush()
            Response.Clear()
        End If

        Dim diff
        diff = Vb6.Timer() - Me.PageStartTime

        strError = strError & vbCrLf & Request.ServerVariables("URL") & "?" & Request.QueryString().ToString() & vbCrLf & "UserName = " & UserName & vbCrLf & "PageLoadTime = " & FormatNumber(diff, 2) & vbCrLf

        If InStr(strError, "timeout") Then
            ' the error was due to a timeout.
            '  the Application variable to indicate the time of this.
            ' MM web page can disable certain task intensive features while timeout phase is in play	
            Application.Lock()
            Application("TIMEOUT") = Now()
            Application.UnLock()
        End If

        If InStr(strError, "registry") Or InStr(strError, "temporary") Then
            ' App Pool reset needed for:
            '   [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key 
            '   Temporary (volatile) Jet DSN for process 0xd98 Thread 0x1ec DBC 0x9b6b62c Jet'. 
            ' or
            '   [Microsoft][ODBC Microsoft Access Driver] Not enough space on temporary disk.
            '   The IIS account needs read/write access to the database folder, or .mdb file missing
            ' but not:
            '   /Message/MessageAdmin/Message.asp A=Admin&S=676&I=-3|3649|80040e14|
            '   [Microsoft][ODBC_Microsoft_Access_Driver]_Syntax_error_(missing_operator)_in_query_expression'   'tab_Messages.LocationIndex_=_4_AND_(tab_Messages.Msg_LastName_LIKE_'%collins%'_OR_tab_Messages.Msg_FullID_LIKE_'%collins%')'   AND_(tab_Messages.Msg_FirstName_LIKE_'%gordon%'_OR_tab_Messages.Msg_FullID_LIKE_'%gordon%')'   AND_tab_Messages.Msg_TeamIndex_=_39_AND_tab_Messages.Msg_Index_>='
            strError = "Message Manager is down" & vbCrLf & "Recycle the Application pool" & vbCrLf & strError
        End If

        ' write it to a log file
        ' strError could have PII in it due to the sSqlString string so don't email the actual error
        Dim bStoreSuccess
        bStoreSuccess = Me.StoreToLog(strError)
        If bStoreSuccess = True Then
            ' log success
            If bShow = True Then
                Response.Write("<font color=""green"">Log File write successful.</font><br>")
            End If
            strError = "<font color=""green"">Log File write successful.</font><br><br>"
        Else
            ' log failure
            ' retain strError message for display since it wasn't written to a logfile
            strError = "<font color=""red"">Log File write failure.</font><br><br>" & strError
            If bShow = True Then
                Response.Write(strError)
            End If
        End If



        If Response.Buffer = True And bShow = True Then
            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
            Response.Flush()
            Response.Clear()
        End If

        ' send an email to check logfile
        _clsMessageVAR.EmailActive = "Yes"
        strError = "Check LogFiles for " & _clsMessageVAR.WebAdminURL & "?A=Setup&menu=LogFiles" & vbCrLf & vbCrLf & strError
        If Me.SendTheMessage(_clsMessageVAR.GProgrammer, strError) = True Then
            ' email sent
            If bShow = True Then
                Response_WriteLine("<font color=""green"">Outage Email sent to " & _clsMessageVAR.GProgrammer & "</font><br><br>")
            End If
        Else
            If bShow = True Then
                ' email send failure
                Response_WriteLine("<font color=""red"">Outage Email send failure.</font><br><br>")
            End If
        End If

        If bShow = True Then
            Me.Debug("Local")
        End If

        If Response.Buffer = True And bShow = True Then
            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
            Response.Flush()
            Response.Clear()
        End If

        ' Reset the Application Pool
        If InStr(strError, "registry") Or InStr(strError, "temporary") Then
            'A handy adjunct to this is the iisapp.vbs script on W2003, 
            ' which lets you enumerate web apps and their corresponding app pool processes.
            ' http://technet2.microsoft.com/WindowsServer/en/Library/30b55aee-c3a4-402a-a98b-46fc194299ec1033.mspx?mfr=true
            ' cscript //NoLogo c:\windows\system32\iisapp.vbs /a AppPoolMessage /r
            _clsMessageVAR.ResetAppPool()
        End If
        If bQuit = True Then
            Response.End()
        Else
            ' wait 2 seconds before returning, let sSqlString overload ease up before repeating the action
            Me.Sleep(2)
        End If
    End Sub

    Function Sleep(seconds)
        ' this method of sleeping has no cpu utilization
        Dim oShell, cmd
        oShell = Vb6.CreateObject("Wscript.Shell")
        cmd = "%COMSPEC% /c timeout " & seconds & " /nobreak"
        oShell.Run(cmd, 0, 1)
        oShell = Nothing
    End Function

    Function StoreToLog(MSG)
        ' returns:
        '   true = send successful
        '   false = send failure.  
        ' open log file in logs folder of MessageAdmin subfolder

        Const ForAppending = 8
        Dim mappath
        Dim wfilename, wfilepath
        Dim fso, f
        Dim bSuccess
        bSuccess = False

        If MSG = "" Then
            ' nothing to store, Nothing mesage
        Else
            MSG = Replace(MSG, "<br>", vbCrLf) & vbCrLf

            ' "yyyy-mm-dd.txt"
            wfilename = DatePart("yyyy", theDate) & "-" & DatePart("m", theDate) & "-" & DatePart("d", theDate) & ".txt"

            mappath = Server.MapPath(".")
            ' could be "d:\wwwroot\Message"
            ' or "d:\wwwroot\Message\MessageAdmin"
            ' end result "d:\wwwroot\Message\MessageAdmin\logs\yyyy-mm-dd.txt"
            If _clsMessageVAR.BDebug = True Then
                Response.Write("mappath=" & mappath & "<br>")
            End If

            wfilepath = mappath & "\logs\" & wfilename

            If _clsMessageVAR.BDebug = True Then
                Response.Write("wfilepath=" & wfilepath & "<br>")
            End If

            fso = Vb6.CreateObject("Scripting.FileSystemObject")
            If fso.FileExists(wfilepath) Then
                ' append today's log

                On Error Resume Next
                f = fso.OpenTextFile(wfilepath, ForAppending)
                If Err.Number <> 0 Then
                    ' read only because somebody is locking it
                    Response.Write("<p><font color=red>Error: " & Err.Description & "<br>READ ONLY attribute exists on logfile.</font></p>")
                    ' do NOT call errorhandler, errorhandler calls this.
                Else
                    ' writeLine adds a new line after
                    On Error Resume Next
                    f.WriteLine(theDate & "@" & DateTime.Now.AddHours(dTimezoneOffset) & ": " & MSG)
                    If Err.Number <> 0 Then
                        Response.Write("<p><font color=red>Error: " & Err.Description & "<br>Could not append to logfile.</font></p>")
                    Else
                        bSuccess = True
                    End If
                    bSuccess = True
                End If
                On Error GoTo 0
                f.Close() ' close logfile	
                f = Nothing

            Else
                ' open new log

                ' true means to overwrite
                ' false means return error if it exists
                On Error Resume Next
                f = fso.CreateTextFile(wfilepath, False)
                If Err.Number <> 0 Then
                    ' read only because somebody is locking it
                    Response.Write("<p><font color=red>Error: " & Err.Description & "<br>READ ONLY attribute exists on logfile.</font></p>")
                    ' do NOT call errorhandler, errorhandler calls this.
                Else
                    ' writeLine adds a new line after
                    On Error Resume Next
                    f.WriteLine(theDate & "@" & DateTime.Now.AddHours(dTimezoneOffset) & ": " & MSG)
                    If Err.Number <> 0 Then
                        Response.Write("<p><font color=red>Error: " & Err.Description & "<br>Could not write to new logfile.</font></p>")
                    Else
                        bSuccess = True
                    End If
                End If
                On Error GoTo 0
                f.Close() ' close logfile
                f = Nothing

            End If ' FileExists
            fso = Nothing
        End If ' MSG = ""

        StoreToLog = bSuccess
    End Function

    Function SendTheMessage(MSGto, MSG)
        ' returns:
        '   true = send successful
        '   false = send failure.  
        '   the "function caller" will store the send results to a database and then later can re-send the failed ones

        Dim emailTo, emailFrom, emailCC
        ' TO
        If MSGto = "" Then
            ' SKIP emailing.  Nobody defined to receive it.
            Response.Write("<p>Not sending email, no recipients defined.</p>")
            SendTheMessage = True
        Else
            ' TO, part 2
            If _clsMessageVAR.EmailActive = "Yes" Then
                emailTo = MSGto
                Response.Write("<p>Sending to: " & MSGto & "</p>")
            Else
                emailTo = _clsMessageVAR.AdminEmailAddress
                Response.Write("<p>System Wide Email is off else would have sent to: " & MSGto & ".<br>Sending to " & emailTo & " instead.</p>")
            End If

            ' send the IIS buffer in case the page hangs due to mailserver offline, 
            ' calms the user's nerves about a white screen and them hitting refresh
            If Response.Buffer = True Then
                'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                Response.Flush()
            End If

            ' CC
            'emailCC = _clsMessageVAR.AdminEmailAddress

            ' FROM
            'emailFrom = _clsMessageVAR.AdminEmailAddress
            emailFrom = _clsMessageVAR.AdminEmailAddress

            ' SMTP object creation

            ' ************************ BEGIN MAIL SETUP OPTIONS *****************
            '
            Dim sch, cdoConfig
            sch = "http://schemas.microsoft.com/cdo/configuration/"
            cdoConfig = Vb6.CreateObject("CDO.Configuration")
            cdoConfig.Fields.Item(sch & "sendusing") = 2 ' 1 = pickup directory, 2 = over the network
            cdoConfig.Fields.Item(sch & "smtpserver") = _clsMessageVAR.EmailServer
            cdoConfig.Fields.Item(sch & "smtpconnectiontimeout") = 15 ' 30 is default if not specified
            cdoConfig.fields.update()
            '
            ' ************************** END MAIL SETUP OPTIONS *****************


            ' ************************ BEGIN MAIL SETUP OPTIONS *****************
            '
            Dim message
            message = Vb6.CreateObject("CDO.Message")
            message.Configuration = cdoConfig

            message.To = emailTo
            message.From = emailFrom
            ' removing CC, getting too many emails
            ' bounced messages still return to .From, that is good enough
            'message.CC = emailCC
            message.subject = _clsMessageVAR.WebName
            'message.TextBody = MSG
            message.HTMLBody = MSG
            'message.Importance = 2 ' High
            'message.Priority = 2 ' High
            On Error Resume Next
            message.Send
            If Err.Number <> 0 Then
                ' prepare to send again later
                SendTheMessage = False
            Else
                ' store it as successful
                SendTheMessage = True
            End If
            On Error GoTo 0
            message = Nothing
            '
            ' ************************** END MAIL SETUP OPTIONS *****************

            ' SMTP object destruction
            cdoConfig = Nothing

        End If
    End Function

    Function ContainsComma(s As String)
        Dim bReturn As Boolean = False

        If InStr(s, ",") Then
            bReturn = True
        Else
            bReturn = False
        End If

        ContainsComma = bReturn

    End Function

    Function SingleSite()
        ' Prediction order: 3 / 3
        ' SingleSite = "000" if multiple sites, or the 3 letter site code if only 1 site
        ' SingleSite is a pointer to a text value
        '   unique site text in table tab_Sites.Si_SiteNum
        '   unique site text in table tab_Locations.Lo_SiteNum
        '   unique site text in tab_Admins.Adm_SiteNum
        ' don't use Admins table, as could have MasterAdmins (sitenum=000) instead of the individual site

        ' works in Access, not sSqlString:
        '    sSqlString = "SELECT COUNT(tab_Sites.Si_SiteNum) AS THECOUNT FROM (SELECT DISTINCT(tab_Sites.Si_SiteNum) FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes');"
        ' this works in Access and sSqlString:
        '    sSqlString = "SELECT COUNT(derived_tab_Sites.Si_SiteNum) AS THECOUNT FROM (SELECT DISTINCT(tab_Sites.Si_SiteNum) FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes') AS derived_tab_Sites;"
        ' Does not need to query uniques:  Return 0, 1, or something > 1.


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = "SELECT COUNT(tab_Sites.Si_SiteNum) AS THECOUNT FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes';"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                SingleSite = "000"
                ' cannot   Me.SiteName 
                ' cannot predict S
            Else
                sqlDataReader.Read()

                If _clsMessageVAR.BDebug = True Then
                    Response.Write("Sites.thecount = " & sqlDataReader.Item("THECOUNT") & "<br>")
                End If
                If sqlDataReader.Item("THECOUNT") = 1 Then
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    '  to the 1 site
                    MyCommand.CommandText = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes';"
                    sqlDataReader = MyCommand.ExecuteReader
                    If Not sqlDataReader.HasRows Then
                        SingleSite = "000"
                    Else
                        sqlDataReader.Read()

                        If IsDBNull(sqlDataReader.Item("Si_SiteNum")) Then
                            SingleSite = "000"
                            S = "000" ' override earlier global settings
                        Else
                            SingleSite = sqlDataReader.Item("Si_SiteNum")
                            S = sqlDataReader.Item("Si_SiteNum") ' override earlier global settings
                        End If
                        If IsDBNull(sqlDataReader.Item("Si_Name")) Then
                            ' retain global setting
                        Else
                            Me.SiteName = sqlDataReader.Item("Si_Name") ' override earlier global settings
                        End If
                    End If
                Else
                    '  to 000
                    SingleSite = "000"
                    ' cannot   Me.SiteName 
                    ' cannot predict S
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        If _clsMessageVAR.BDebug = True Then
            Response.Write("MyCommand.CommandText = " & MyCommand.CommandText & "<br>")
        End If
    End Function

    Function SingleLocation()
        ' single Location (Location) auto-selection
        ' SingleLocation is a pointer to a number / autonumber
        '   unique index value in table tab_Locations.Lo_Index
        '   unique index value in table tab_Teams.Te_LocationIndex

        ' MSAccess works with the SELECT DISTINCT but sSqlString does not:
        '   sSqlString = "SELECT COUNT(tab_Locations.Lo_Index) AS THECOUNT FROM (SELECT DISTINCT(tab_Locations.Lo_Index) FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & whatsite & "' AND tab_Locations.Lo_Active = 'Yes');"
        ' this works in Access and sSqlString:
        '	sSqlString = "SELECT COUNT(derived_tab_Sites.Lo_Index) AS THECOUNT FROM (SELECT DISTINCT(tab_Locations.Lo_Index) FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & whatsite & "' AND tab_Locations.Lo_Active = 'Yes') AS derived_tab_Sites;"
        ' Does not need to query uniques:  Return 0, 1, or something > 1.


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = "SELECT COUNT(tab_Locations.Lo_Index) AS THECOUNT FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & Me.Whatsite & "' AND tab_Locations.Lo_Active = 'Yes';"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                SingleLocation = 0
            Else
                sqlDataReader.Read()

                If _clsMessageVAR.BDebug = True Then
                    Response.Write("Locations.thecount = " & sqlDataReader.Item("THECOUNT") & "<br>")
                End If
                If sqlDataReader.Item("THECOUNT") = 1 Then
                    '  "SingleLocation" to the 1 Location's "tab_Locations.Lo_Index"
                    'sSqlString = "SELECT tab_Admins.Adm_SiteNum FROM tab_Admins WHERE tab_Admins.Adm_SiteNum <> '000';"
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    MyCommand.CommandText = "SELECT tab_Locations.Lo_Index FROM tab_Locations WHERE tab_Locations.Lo_Active = 'Yes' AND tab_Locations.Lo_SiteNum = '" & Me.Whatsite & "';"
                    sqlDataReader = MyCommand.ExecuteReader
                    If Not sqlDataReader.HasRows Then
                        SingleLocation = 0
                    Else
                        sqlDataReader.Read()
                        SingleLocation = sqlDataReader.Item("Lo_Index")
                    End If
                Else
                    '  to 0
                    SingleLocation = 0
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        If _clsMessageVAR.BDebug = True Then
            Response.Write("MyCommand.CommandText = " & MyCommand.CommandText & "<br>")
        End If
    End Function

    Function SingleTeam(LocationIndex)
        ' returns "tab_Teams.Te_Index" if this member is for only 1 team
        ' else returns 0


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = "SELECT COUNT(tab_Teams.Te_Index) AS THECOUNT FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & LocationIndex & " AND tab_Teams.Te_Active = 'Yes';"

        If LocationIndex.ToString = "" Then
            SingleTeam = 0
        Else
            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                ' MSAccess works with the SELECT DISTINCT but sSqlString does not:
                '   sSqlString = "SELECT COUNT(tab_Teams.Te_Index) AS THECOUNT FROM (SELECT DISTINCT(tab_Teams.Te_Index) FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & LocationIndex & " AND tab_Teams.Te_Active = 'Yes');"
                ' this works in Access and sSqlString:
                '   sSqlString = "SELECT COUNT(derived_tab_Teams.Te_Index) AS THECOUNT FROM (SELECT DISTINCT(tab_Teams.Te_Index) FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & LocationIndex & " AND tab_Teams.Te_Active = 'Yes') AS derived_tab_Teams;"
                ' Does not need to query uniques:  Return 0, 1, or something > 1.

                If _clsMessageVAR.BDebug = True Then
                    Response.Write("SQL = " & MyCommand.CommandText & "<br>")
                End If
                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    SingleTeam = 0
                Else
                    sqlDataReader.Read()

                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("Team.thecount = " & sqlDataReader.Item("THECOUNT") & "<br>")
                    End If
                    If sqlDataReader.Item("THECOUNT") = 1 Then
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()

                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        MyCommand.CommandText = "SELECT tab_Teams.Te_Index FROM tab_Teams WHERE tab_Teams.Te_Active = 'Yes' AND tab_Teams.Te_LocationIndex = " & LocationIndex & ";"
                        '  "SingleTeam" to the 1 Member's "tab_Teams.Te_Index"
                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            SingleTeam = 0
                        Else
                            sqlDataReader.Read()
                            SingleTeam = sqlDataReader.Item("Te_Index")
                        End If
                    Else
                        '  to 0
                        SingleTeam = 0
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If
    End Function

    Function GetADPath(sDomain)
        ' returns strAdsPath based on the sDomain in the format of "VHAxx" etc
        ' if not found returns ","

        ' sample strAdsPath = "OU=Users,OU=Madison (MAD),OU=VISN12,DC=v12,DC=med,DC=va,DC=gov"
        ' sample strDomain = "OU=Users,OU=Madison (MAD),OU=VISN12"
        ' sample u_location = "DC=v12,DC=med,DC=va,DC=gov"

        Dim strAdsPath, strDomain, u_location
        If sDomain <> "" Then
            sDomain = UCase(sDomain)
        End If

        If _clsMessageVAR.BDebug = True Then
            Response.Write("sDomain=" & sDomain & "<br>")
        End If

        Select Case sDomain
            Case "VHA01"
                'strDomain = "OU=VISN01"
                strDomain = ""
                u_location = "DC=v01,DC=med,DC=va,DC=gov"
            Case "VHA02"
                'strDomain = "OU=VISN02"
                strDomain = ""
                u_location = "DC=v02,DC=med,DC=va,DC=gov"
            Case "VHA03"
                'strDomain = "OU=VISN03"
                strDomain = ""
                u_location = "DC=v03,DC=med,DC=va,DC=gov"
            Case "VHA04"
                'strDomain = "OU=VISN04"
                strDomain = ""
                u_location = "DC=v04,DC=med,DC=va,DC=gov"
            Case "VHA05"
                'strDomain = "OU=VISN05"
                strDomain = ""
                u_location = "DC=v05,DC=med,DC=va,DC=gov"
            Case "VHA06"
                'strDomain = "OU=VISN06"
                strDomain = ""
                u_location = "DC=v06,DC=med,DC=va,DC=gov"
            Case "VHA07"
                'strDomain = "OU=VISN07"
                strDomain = ""
                u_location = "DC=v07,DC=med,DC=va,DC=gov"
            Case "VHA08"
                'strDomain = "OU=VISN08"
                strDomain = ""
                u_location = "DC=v08,DC=med,DC=va,DC=gov"
            Case "VHA09"
                ' there is a space in "VISN 09" OU name
                'strDomain = "OU=VISN 09"
                strDomain = ""
                u_location = "DC=v09,DC=med,DC=va,DC=gov"
            Case "VHA10"
                'strDomain = "OU=VISN10"
                strDomain = ""
                u_location = "DC=v10,DC=med,DC=va,DC=gov"
            Case "VHA11"
                'strDomain = "OU=VISN11"
                strDomain = ""
                u_location = "DC=v11,DC=med,DC=va,DC=gov"
            Case "VHA12"
                'strDomain = "OU=VISN12"
                strDomain = ""
                u_location = "DC=v12,DC=med,DC=va,DC=gov"
        'Case "VHA13"
        '	'strDomain = "OU=VISN13"
        '	strDomain = ""
        '	u_location = "DC=v13,DC=med,DC=va,DC=gov"
        'Case "VHA14"
        '	'strDomain = "OU=VISN14"
        '	strDomain = ""
        '	u_location = "DC=v14,DC=med,DC=va,DC=gov"
            Case "VHA15"
                'strDomain = "OU=VISN15"
                strDomain = ""
                u_location = "DC=v15,DC=med,DC=va,DC=gov"
            Case "VHA16"
                'strDomain = "OU=VISN16"
                strDomain = ""
                u_location = "DC=v16,DC=med,DC=va,DC=gov"
            Case "VHA17"
                ' there is a space in "VISN 17" OU name
                'strDomain = "OU=VISN 17"
                strDomain = ""
                u_location = "DC=v17,DC=med,DC=va,DC=gov"
            Case "VHA18"
                'strDomain = "OU=VISN18"
                strDomain = ""
                u_location = "DC=v18,DC=med,DC=va,DC=gov"
            Case "VHA19"
                'strDomain = "OU=VISN19"
                strDomain = ""
                u_location = "DC=v19,DC=med,DC=va,DC=gov"
            Case "VHA20"
                'strDomain = "OU=VISN20"
                strDomain = ""
                u_location = "DC=v20,DC=med,DC=va,DC=gov"
            Case "VHA21"
                'strDomain = "OU=VISN21"
                strDomain = ""
                u_location = "DC=v21,DC=med,DC=va,DC=gov"
            Case "VHA22"
                ' there is a space in "VISN 22" OU name
                'strDomain = "OU=VISN 22"
                strDomain = ""
                u_location = "DC=v22,DC=med,DC=va,DC=gov"
            Case "VHA23"
                ' there is a space in "VISN 23" OU name
                'strDomain = "OU=VISN 23"
                strDomain = ""
                u_location = "DC=v23,DC=med,DC=va,DC=gov"

            Case "R01"
                strDomain = ""
                u_location = "DC=r01,DC=med,DC=va,DC=gov"
            Case "R02"
                strDomain = ""
                u_location = "DC=r02,DC=med,DC=va,DC=gov"
            Case "R03"
                strDomain = ""
                u_location = "DC=r03,DC=med,DC=va,DC=gov"
            Case "R04"
                strDomain = ""
                u_location = "DC=r04,DC=med,DC=va,DC=gov"

            Case "VHAMASTER"
                strDomain = ""
                u_location = "DC=vha,DC=med,DC=va,DC=gov"

            Case "VHA"
                strDomain = ""
                u_location = "DC=vha,DC=med,DC=va,DC=gov"

            Case "VA"
                strDomain = ""
                u_location = "DC=va,DC=gov"

        ' med.va.gov has no users

            Case "VBA"
                strDomain = ""
                u_location = "DC=vba,DC=va,DC=gov"

            Case "DVA"
                strDomain = ""
                u_location = "DC=dva,DC=va,DC=gov"

            Case Else
                strDomain = ""
                u_location = ""
        End Select

        If strDomain = "" Then
            strAdsPath = u_location
        Else
            strAdsPath = strDomain & "," & u_location
        End If
        If _clsMessageVAR.BDebug = True Then
            Response.Write("strAdsPath=" & strAdsPath & "<br>")
        End If

        ' code for Nothing results = ","
        If strAdsPath = "" Then
            strAdsPath = ","
        End If

        GetADPath = strAdsPath
    End Function
    Function GetMessageReason(Index)
        Dim sReason As String = ""
        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = "SELECT Msg_Reason FROM tab_Messages WHERE tab_Messages.Msg_Index = " & Index & ";"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            If _clsMessageVAR.BDebug = True Then
                Response.Write("SQL = " & MyCommand.CommandText & "<br>")
            End If
            sqlDataReader = MyCommand.ExecuteReader

            sqlDataReader.Read()
            sReason = sqlDataReader.Item("Msg_Reason")
            GetMessageReason = sReason
        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Function AscB(value As Char) As Byte
        Return System.Convert.ToByte(value)
    End Function

    Function ByteArrToHexString(ByVal bytes As Byte()) As String
        Dim Result As New System.Text.StringBuilder(bytes.Length * 2)
        Dim Part As String
        For Each b As Byte In bytes
            Part = Conversion.Hex(b)
            If Part.Length = 1 Then Part = "0" & Part
            Result.Append(Part)
        Next
        Return Result.ToString().Trim
    End Function

    Function PollAdminNameForLogin(sLogin)
        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        PollAdminNameForLogin = "NAME UNKNOWN"

        MyCommand.CommandText = "SELECT Adm_Name FROM tab_Admins WHERE Adm_UserName = '" & sLogin & "';"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                ' Finally try AD lookup and is a known performance hit...
                PollAdminNameForLogin = PollADforFullName(sLogin)
            Else
                PollAdminNameForLogin = sqlDataReader.Item("Adm_Name")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Function PollMemberNameForLogin(sUserid)
        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        PollMemberNameForLogin = "NAME UNKNOWN"

        MyCommand.CommandText = "SELECT Me_Name FROM tab_Members WHERE Me_UserName = '" & sUserid & "';"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                PollMemberNameForLogin = PollAdminNameForLogin(sUserid)
            Else
                PollMemberNameForLogin = sqlDataReader.Item("Me_Name")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Function PollADforFullName(sUserLogin)

        ' not yet cached, load SID from AD

        'const ADS_SCOPE_BASE = 0		' used for root search only
        'const ADS_SCOPE_ONELEVEL = 1	' used for one-level search
        Const ADS_SCOPE_SUBTREE = 2     ' used for child tree search

        Dim found, ADerror, strFirstname, strLastname, strFullname
        found = 0
        ADerror = 8  ' 8 means initialized
        strFullname = "NOTFOUND"

        Dim RS
        Dim strRS, strCON
        Dim objConnection, objCommand

        'SAMPLE strAdsPath:   "OU=Users,OU=Madison (MAD),OU=VISN12,DC=v12,DC=med,DC=va,DC=gov"
        Dim strAdsPath

        ' GLOBAL KNOWN: logged in UserName in form of "VHA12\VHAMADSmithC"
        Dim aDU, sUser, sDomain
        aDU = Split(sUserLogin & "\zzz\zzz", "\")
        sUser = aDU(1)
        ' Domain not provided in search string override, load it from logged in user
        If sDomain = "" Then
            sDomain = aDU(0)
        End If
        If sDomain <> "None" And sUser <> "None" And sDomain <> "zzz" And sUser <> "zzz" Then

            ' compute the ADS PATH based on logged on user's domain
            strAdsPath = Me.GetADPath(sDomain)

            If strAdsPath <> "," Then
                RS = Vb6.CreateObject("ADODB.RecordSet")
                objConnection = Vb6.CreateObject("ADODB.Connection")
                objCommand = Vb6.CreateObject("ADODB.Command")

                objConnection.Provider = "ADsDSOObject"

                ' W USERNAME
                strCON = "Provider=ADsDSOObject;Password=" & _clsMessageVAR.uAccessPassword & ";User ID=" & _clsMessageVAR.uAccessId & ";Encrypt Password=True;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648"
                objConnection.Open(strCON)
                objCommand.ActiveConnection = objConnection
                objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
                objCommand.Properties("Size Limit") = 10
                objCommand.Properties("Page Size") = 10
                objCommand.Properties("Time Limit") = 15
                objCommand.Properties("Sort on") = "sAMAccountName"

                strRS = "SELECT cn, givenName, SN, mail, sAMAccountName, title FROM 'GC://" & strAdsPath & "' WHERE objectClass = 'user' and sAMAccountName = '" & sUser & "'"
                If _clsMessageVAR.BDebug = True Then
                    Response.Write("strRS=" & strRS & "<br>")
                End If
                objCommand.CommandText = strRS
                'Execute the query.
                On Error Resume Next
                RS = objCommand.Execute()
                If (Err.Number <> 0) Then
                    'Response.Write(Err.Number & " on Execute" & "<br>")
                    ADerror = 3
                Else
                    If Not RS.EOF Then
                        ' Navigate the record 
                        RS.MoveFirst
                        'Response.Write("Found<br>")
                        'strFullname = RS.Fields("cn").Value
                        strFirstname = RS.Fields("givenName").Value
                        strLastname = RS.Fields("SN").Value
                        found = 1
                    Else
                        'Response.Write("Not Found<br>")
                        ADerror = 2
                    End If
                End If ' err.number
                RS = Nothing

                ' Close AD Objects
                objCommand = Nothing

                objConnection.Close()
                objConnection = Nothing

            Else
                ADerror = 5
            End If ' strAdsPath = ","
        Else
            ADerror = 6
        End If ' sDomain or sUser = "zzz" or "None"


        If found = 1 Then
            strFullname = strFirstname & " " & strLastname
        Else
            ' the IT account's OU not known?  Email the info to admin to troubleshoot

            Select Case ADerror
                Case 8
                    ' initialized
                    strFullname = "AD error variable initialized. Unknown error."
                Case 6
                    strFullname = "sDomain lookup error, no Domain on logged in user account."
                Case 5
                    strFullname = "sDomain lookup error, unable to determine DC strAdsPath."
                Case 3
                    strFullname = "DC Lookup error, unable to perform LDAP query."
                Case 2
                    strFullname = "Username not found in AD OU."
                Case Else
                    ' what the ???
                    strFullname = "Unknown AD lookup error"
            End Select

        End If

        PollADforFullName = strFullname

    End Function

    Function PollADforSID()
        ' polls AD for global UserName in format of "VHA12\VHAMADTESTF"
        ' called by CheckAdmin()
        ' returns the SID if found
        ' returns "NOTFOUND" if not found
        ' returns "DCERROR" if error doing ADO lookup

        Dim appSID
        appSID = Application(UCase(Me.UserName))
        If appSID = "" Then
            ' not yet cached, load SID from AD

            'const ADS_SCOPE_BASE = 0		' used for root search only
            'const ADS_SCOPE_ONELEVEL = 1	' used for one-level search
            Const ADS_SCOPE_SUBTREE = 2     ' used for child tree search

            Dim found, ADerror, ADSID
            found = 0
            ADerror = 8  ' 8 means initialized
            ADSID = "NOTFOUND"

            Dim mailmsg  ' used if not found

            Dim RS
            Dim strRS, strCON
            Dim objConnection, objCommand

            'SAMPLE strAdsPath:   "OU=Users,OU=Madison (MAD),OU=VISN12,DC=v12,DC=med,DC=va,DC=gov"
            Dim strAdsPath

            ' GLOBAL KNOWN: logged in UserName in form of "VHA12\VHAMADSmithC"
            Dim aDU, sUser, sDomain
            aDU = Split(Me.UserName & "\zzz\zzz", "\")
            sUser = aDU(1)
            ' Domain not provided in search string override, load it from logged in user
            If sDomain = "" Then
                sDomain = aDU(0)
            End If
            If sDomain <> "None" And sUser <> "None" And sDomain <> "zzz" And sUser <> "zzz" Then

                ' compute the ADS PATH based on logged on user's domain
                strAdsPath = Me.GetADPath(sDomain)

                If strAdsPath <> "," Then
                    RS = Vb6.CreateObject("ADODB.RecordSet")
                    objConnection = Vb6.CreateObject("ADODB.Connection")
                    objCommand = Vb6.CreateObject("ADODB.Command")

                    objConnection.Provider = "ADsDSOObject"

                    ' W USERNAME
                    strCON = "Provider=ADsDSOObject;Password=" & _clsMessageVAR.uAccessPassword & ";User ID=" & _clsMessageVAR.uAccessId & ";Encrypt Password=True;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648"
                    objConnection.Open(strCON)
                    objCommand.ActiveConnection = objConnection
                    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
                    objCommand.Properties("Size Limit") = 10
                    objCommand.Properties("Page Size") = 10
                    objCommand.Properties("Time Limit") = 15
                    objCommand.Properties("Sort on") = "sAMAccountName"

                    strRS = "SELECT objectSid FROM 'GC://" & strAdsPath & "'" & " WHERE objectClass = 'user' and sAMAccountName = '" & sUser & "'"
                    'strRS = "SELECT objectSid FROM 'LDAP://" & strAdsPath & "' WHERE objectClass = 'user' and sAMAccountName = '" & sUser & "'"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("strRS=" & strRS & "<br>")
                    End If
                    objCommand.CommandText = strRS
                    'Execute the query.
                    On Error Resume Next
                    RS = objCommand.Execute()
                    If (Err.Number <> 0) Then
                        'Response.Write(Err.Number & " on Execute" & "<br>")
                        ADerror = 3
                    Else
                        If Not RS.EOF Then
                            ' Navigate the record 
                            RS.MoveFirst
                            While Not RS.EOF
                                'Response.Write("Found<br>")
                                ADSID = Me.ByteArrToHexString(RS.Fields("objectSid").Value)
                                RS.MoveNext
                            End While
                            found = 1
                        Else
                            'Response.Write("Not Found<br>")
                            ADerror = 2
                        End If
                    End If ' err.number
                    RS = Nothing

                    ' Close AD Objects
                    objCommand = Nothing

                    objConnection.Close()
                    objConnection = Nothing

                Else
                    ADerror = 5
                End If ' strAdsPath = ","
            Else
                ADerror = 6
            End If ' sDomain or sUser = "zzz" or "None"


            If found = 1 Then
                ' cache the SID in Application Variables
                Application.Lock()
                Application(UCase(Me.UserName)) = ADSID
                Application.UnLock()
            Else
                ' the IT account's OU not known?  Email the info to admin to troubleshoot

                Select Case ADerror
                    Case 8
                        ' initialized
                        mailmsg = "AD error variable initialized. Unknown error." & vbCrLf
                        ADSID = "DCERROR"
                    Case 6
                        mailmsg = "sDomain lookup error, no Domain on logged in user account." & vbCrLf
                        ADSID = "DCERROR"
                    Case 5
                        mailmsg = "sDomain lookup error, unable to determine DC strAdsPath." & vbCrLf
                        ADSID = "DCERROR"
                    Case 3
                        mailmsg = "DC Lookup error, unable to perform LDAP query." & vbCrLf
                        ADSID = "DCERROR"
                    Case 2
                        mailmsg = "Username not found in AD OU." & vbCrLf
                        ADSID = "NOTFOUND"
                    Case Else
                        ' what the ???
                        mailmsg = "Unknown AD lookup error" & vbCrLf
                        ADSID = "DCERROR"
                End Select
                mailmsg = mailmsg & "IP: " & Me.UserIP & vbCrLf
                mailmsg = mailmsg & "UserName: " & UserName & vbCrLf
                mailmsg = mailmsg & "strAdsPath: " & strAdsPath & vbCrLf
                Me.ErrorHandler(mailmsg, False, False)

            End If

            ' SID found in AD, use it
            PollADforSID = ADSID

        Else
            ' SID cached in Application Variables, use it
            PollADforSID = appSID
        End If
    End Function

    Function ADNameSearch(d)
        ' polls Active Directory Global Catalog of the logged in user's domain for the name that was type in the Name form field
        ' d = "Last, First" or "First Last"
        ' Find THESE:
        Dim strFirstname, strLastname, strFullname, strUsername, strEmail, strTitle, strSID
        Dim sDomain, sUser, aDU

        ' OUTPUT in the form of multiple rows of:
        ' strFirstname & strLastname & "_^_" & strEmail & "_^_" & strTitle & "_^_" & strFullname & "_^_" & sDomain & "\" & strUsername & "_^_" & strSID & "_^__ROW_"
        Dim strStructure
        strStructure = ""

        ' Once in a while a super huge search will time out
        Server.ScriptTimeout = 45   ' default 90 on prod server, 10 minutes on test server

        ' break d into strInF and strInL
        Dim strInF, strInL, strInF2, strInL2
        Dim arrIn, tooshort, arrDom
        sDomain = ""
        tooshort = ""
        strInF = ""
        strInF2 = ""
        strInL = ""
        strInL2 = ""
        ' pull off extra spaces
        Do While Right(d, 1) = " "
            d = Left(d, Len(d) - 1)
        Loop
        Do While Left(d, 1) = " "
            d = Right(d, Len(d) - 1)
        Loop
        Do While InStr(d, "  ") > 0
            d = Replace(d, "  ", " ")
        Loop

        If d = "" Then
            tooshort = "Must enter ""First Last"" or ""Last, First"" before searching."
        Else

            ' Optional: Precede name with "vhaxx\" for other domains
            ' Example: d="vha12\Doe, John"
            If InStr(d, "\") Then
                arrDom = Split(d, "\")
                ' fill in "sDomain" with the domain
                sDomain = UCase(arrDom(0))
                ' update "d" with the remaining display name
                d = arrDom(1)
            End If

            If InStr(d, ",") Then
                ' "Last1 Last2, First" (Smith Jackson, Robert)
                ' "Last, First Second" (Jo Ellen Smith
                ' "Last, First"
                ' "Last,First"
                If InStr(d, ", ") Then
                    ' "Last, First"
                    arrIn = Split(d, ", ")
                    strInL = arrIn(0)
                    strInF = arrIn(1)
                Else
                    ' "Last,First"
                    arrIn = Split(d, ",")
                    strInL = arrIn(0)
                    strInF = arrIn(1)
                End If

                ' Too short warning situations
                ' Let through 
                If Len(strInL) = 3 And Len(strInF) = 3 Then
                    ' OK
                    ' "Sue Bay" is a legitimate 3 character first and last name, let 3+3 searches go through
                Else
                    If (Len(strInL) = 3 And Len(strInF) = 2) Or (Len(strInL) = 2 And Len(strInF) = 3) Then
                        ' OK
                        ' "Kim, Su" is a legitimate 3/2 character name, let 2+3 or 3+2 searches go through
                    Else
                        ' fail these
                        If Len(strInL) < 4 And Len(strInF) < 4 Then
                            tooshort = "One of the name fields must be longer than 3 characters, search for longer name or enter manually."
                        End If
                    End If
                End If

            Else
                ' "First Last1 Last2" (Robert Smith Jackson)
                ' "First Second Last" (Jo Ellen Smith)
                ' "First Last"
                ' "First"
                ' "Last"
                If InStr(d, " ") Then
                    ' "First Last"
                    arrIn = Split(d & " zzz", " ")
                    If arrIn(2) = "zzz" Then
                        ' "First Last"
                        strInF = arrIn(0)
                        strInL = arrIn(1)
                    Else
                        ' this is either "First Second Last" or "First Last1 Last2"
                        strInF = arrIn(0) & " " & arrIn(1)
                        strInL = arrIn(2)
                        strInF2 = arrIn(0)
                        strInL2 = arrIn(1) & " " & arrIn(2)
                    End If

                    ' Too short warning situations
                    ' Let through 
                    If Len(strInL) = 3 And Len(strInF) = 3 Then
                        ' OK
                        ' "Sue Bay" is a legitimate 3 character first and last name, let 3+3 searches go through
                    Else
                        If (Len(strInL) = 3 And Len(strInF) = 2) Or (Len(strInL) = 2 And Len(strInF) = 3) Then
                            ' OK
                            ' "Kim, Su" is a legitimate 3/2 character name, let 2+3 or 3+2 searches go through
                        Else
                            ' fail these
                            If Len(strInL) < 4 And Len(strInF) < 4 Then
                                tooshort = "One of the name fields must be longer than 3 characters, search for longer name or enter manually."
                            End If
                        End If
                    End If

                Else
                    strInF = d
                    strInL = ""
                    If Len(strInF) < 5 Then
                        tooshort = "Cannot search single name field less than 5 characters.<br>Enter ""first last"" or ""last, first"" instead."
                    End If
                End If
            End If
        End If

        If _clsMessageVAR.BDebug = True Then
            Response.Write("sDomain=" & sDomain & "<br>")
            Response.Write("strInF=" & strInF & "<br>")
            Response.Write("strInL=" & strInL & "<br>")
            Response.Write("strInF2=" & strInF2 & "<br>")
            Response.Write("strInL2=" & strInL2 & "<br>")
        End If

        If tooshort = "" Then
            ' valid input, seach for it
            ' GLOBAL KNOWN: logged in UserName in form of "VHA12\VHAMADSmithC"

            aDU = Split(Me.UserName & "\zzz\zzz", "\")
            sUser = aDU(1)
            ' Domain not provided in search string override, load it from logged in user
            If sDomain = "" Then
                sDomain = aDU(0)
            End If

            If sDomain <> "None" And sUser <> "None" And sDomain <> "zzz" And sUser <> "zzz" Then

                ' compute the ADS PATH based on computed sDomain
                Dim strAdsPath
                strAdsPath = Me.GetADPath(sDomain)

                If strAdsPath <> "," Then

                    ' ************* START ADO
                    'const ADS_SCOPE_BASE = 0		' used for root search only
                    'const ADS_SCOPE_ONELEVEL = 1	' used for one-level search
                    Const ADS_SCOPE_SUBTREE = 2     ' used for child tree search

                    Dim ADSRS, objConnection, objCommand
                    Dim strRS, strCON
                    ADSRS = Vb6.CreateObject("ADODB.RecordSet")
                    objConnection = Vb6.CreateObject("ADODB.Connection")
                    objCommand = Vb6.CreateObject("ADODB.Command")

                    ' strCON = "Provider=ADsDSOObject;Password=" & u_access_password & ";User ID=" & u_access_id & ";Encrypt Password=True;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648"				
                    objConnection.Provider = "ADsDSOObject"
                    objConnection.Properties("User ID") = _clsMessageVAR.uAccessId
                    objConnection.Properties("Password") = _clsMessageVAR.uAccessPassword
                    objConnection.Properties("Encrypt Password") = True
                    'objConnection.Properties("Mode") = "Read"
                    objConnection.Properties("Bind Flags") = 0
                    objConnection.Properties("ADSI Flag") = -2147483648
                    ' objConnection.Open strCON
                    objConnection.Open()

                    objCommand.ActiveConnection = objConnection
                    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
                    objCommand.Properties("Size Limit") = 20
                    objCommand.Properties("Page Size") = 20
                    objCommand.Properties("Time Limit") = 15 ' server time limit and then obtained results are returned
                    objCommand.Properties("Timeout") = 20    ' seconds, client time out before stopping the search
                    objCommand.Properties("Sort on") = "sAMAccountName"

                    'GivenName 
                    'sn 
                    'sAMAccoutName 
                    'mail 
                    'otherMailbox 
                    'title 
                    'whenCreated 
                    'co 
                    'department 
                    'employeeType 
                    'description 
                    ' WHERE objectClass = 'user' and sAMAccountName = '" & UserName & "'"
                    ' strRS = "SELECT cn, givenName, SN, mail, sAMAccountName, title FROM 'GC://" & strAdsPath & "' WHERE objectClass = 'user' and sAMAccountName = 'vhamadknappg'"
                    If (strInL = "") Then
                        ' single name entered, search both fields for a hit
                        ' when 1 name is entered only strInF will have a value
                        strInF = Replace(strInF, "'", "''")
                        strRS = "SELECT cn, givenName, SN, mail, sAMAccountName, title, objectSid FROM 'GC://" & strAdsPath & "'" & " WHERE objectClass = 'user' and (SN = '" & strInF & "*' or givenName = '" & strInF & "*')"
                    Else
                        ' both names entered
                        strInF = Replace(strInF, "'", "''")
                        strInL = Replace(strInL, "'", "''")
                        If strInF2 = "" And strInL2 = "" Then
                            ' simple "First Last" search
                            strRS = "SELECT cn, givenName, SN, mail, sAMAccountName, title, objectSid FROM 'GC://" & strAdsPath & "'" & " WHERE objectClass = 'user' and SN = '" & strInL & "*' and givenName = '" & strInF & "*'"
                        Else
                            ' this is either "First Second Last" or "First Last1 Last2"
                            strInF2 = Replace(strInF2, "'", "''")
                            strInL2 = Replace(strInL2, "'", "''")
                            strRS = "SELECT cn, givenName, SN, mail, sAMAccountName, title, objectSid FROM 'GC://" & strAdsPath & "'" & " WHERE objectClass = 'user'" & " and (SN = '" & strInL & "*' and givenName = '" & strInF & "*')" & " or (SN = '" & strInL2 & "*' and givenName = '" & strInF2 & "*')"
                        End If

                    End If
                    'Response.Write("strRS=" & strRS & "<br>")
                    objCommand.CommandText = strRS
                    'Execute the query.
                    On Error Resume Next
                    ADSRS = objCommand.Execute()
                    If (Err.Number <> 0) Then
                        Response.Write(Err.Number & " " & Err.Description & "<br>")
                    Else
                        If Not ADSRS.EOF Then
                            ' Navigate the record 
                            Response_WriteLine("<p><font color=""green""><b>" & d & "</b> found in Active Directory " & sDomain & "</font></p>")
                            ADSRS.MoveFirst
                            While Not ADSRS.EOF

                                strFullname = ADSRS.Fields("cn").Value
                                strFirstname = ADSRS.Fields("givenName").Value
                                strLastname = ADSRS.Fields("SN").Value
                                strEmail = ADSRS.Fields("mail").Value
                                strUsername = ADSRS.Fields("sAMAccountName").Value
                                strTitle = ADSRS.Fields("title").Value
                                strSID = Me.ByteArrToHexString(ADSRS.Fields("objectSid").Value)

                                strStructure = strStructure & strFirstname & "_^_" & strLastname & "_^_" & strEmail & "_^_" & strTitle & "_^_" & strFullname & "_^_" & sDomain & "\" & strUsername & "_^_" & strSID & "_^__ROW_"

                                ADSRS.MoveNext
                            End While
                        Else
                            Response_WriteLine("<p><font color=""red""><b>" & d & "</b> not found in Active Directory " & sDomain & "<br><br>Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                            ' return Nothing string ""
                        End If
                    End If ' err.number

                    ' Close AD Objects
                    ADSRS = Nothing
                    objCommand = Nothing
                    objConnection.Close()
                    objConnection = Nothing
                    ' ************* END ADO

                Else
                    ' ADS Path unknown, cannot load from AD
                    ' hard code more CASE statements pointing sDomain to the OU,DC of it.
                    Response_WriteLine("<p><font color=""red"">Domain not available for AD search.</font></p>")
                End If
            Else
                ' logged in user domain not found, cannot load from AD
                Response_WriteLine("<p><font color=""red"">Domain not recognized for AD search.</font></p>")
            End If
        Else
            ' name too short to search for in AD, show error message
            Response_WriteLine("<p><font color=""red"">" & tooshort & "<br><br>Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
        End If '

        ADNameSearch = strStructure
    End Function
    Private Function ValidateADUser(u) As Boolean
        Dim strarr() As String
        Dim strDirEntry As String

        ' called by StrandedUsers action of EditSetup (vs. former CheckADUser() function)

        strarr = u.Split("\")
        If strarr(0) = "" Or strarr(1) = "" Then Return False

        Select Case strarr(0).ToUpper
            Case "VHA01"
                strDirEntry = "DC=v01,DC=med,DC=va,DC=gov"
            Case "VHA02"
                strDirEntry = "DC=v02,DC=med,DC=va,DC=gov"
            Case "VHA03"
                strDirEntry = "DC=v03,DC=med,DC=va,DC=gov"
            Case "VHA04"
                strDirEntry = "DC=v04,DC=med,DC=va,DC=gov"
            Case "VHA05"
                strDirEntry = "DC=v05,DC=med,DC=va,DC=gov"
            Case "VHA06"
                strDirEntry = "DC=v06,DC=med,DC=va,DC=gov"
            Case "VHA07"
                strDirEntry = "DC=v07,DC=med,DC=va,DC=gov"
            Case "VHA08"
                strDirEntry = "DC=v08,DC=med,DC=va,DC=gov"
            Case "VHA09"
                strDirEntry = "DC=v09,DC=med,DC=va,DC=gov"
            Case "VHA10"
                strDirEntry = "DC=v10,DC=med,DC=va,DC=gov"
            Case "VHA11"
                strDirEntry = "DC=v11,DC=med,DC=va,DC=gov"
            Case "VHA12"
                strDirEntry = "DC=v12,DC=med,DC=va,DC=gov"
        'Case "VHA13"
        '	strDirEntry = "DC=v13,DC=med,DC=va,DC=gov"
        'Case "VHA14"
        '	strDirEntry = "DC=v14,DC=med,DC=va,DC=gov"
            Case "VHA15"
                strDirEntry = "DC=v15,DC=med,DC=va,DC=gov"
            Case "VHA16"
                strDirEntry = "DC=v16,DC=med,DC=va,DC=gov"
            Case "VHA17"
                strDirEntry = "DC=v17,DC=med,DC=va,DC=gov"
            Case "VHA18"
                strDirEntry = "DC=v18,DC=med,DC=va,DC=gov"
            Case "VHA19"
                strDirEntry = "DC=v19,DC=med,DC=va,DC=gov"
            Case "VHA20"
                strDirEntry = "DC=v20,DC=med,DC=va,DC=gov"
            Case "VHA21"
                strDirEntry = "DC=v21,DC=med,DC=va,DC=gov"
            Case "VHA22"
                strDirEntry = "DC=v22,DC=med,DC=va,DC=gov"
            Case "VHA23"
                strDirEntry = "DC=v23,DC=med,DC=va,DC=gov"
            Case "R01"
                strDirEntry = "DC=r01,DC=med,DC=va,DC=gov"
            Case "R02"
                strDirEntry = "DC=r02,DC=med,DC=va,DC=gov"
            Case "R03"
                strDirEntry = "DC=r03,DC=med,DC=va,DC=gov"
            Case "R04"
                strDirEntry = "DC=r04,DC=med,DC=va,DC=gov"
            Case "VHAMASTER"
                strDirEntry = "DC=vha,DC=med,DC=va,DC=gov"
            Case "VHA"
                strDirEntry = "DC=vha,DC=med,DC=va,DC=gov"
            Case "VA"
                strDirEntry = "DC=va,DC=gov"
            Case "VBA"
                strDirEntry = "DC=vba,DC=va,DC=gov"

            Case Else
                Return False
        End Select

        Dim retval As Boolean = False
        Dim adRoot As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry("GC://" & strDirEntry)
        Dim filter As String = String.Format("(&(ObjectClass=person)(sAMAccountName={0}))", strarr(1))
        Dim searcher As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(adRoot)

        searcher.Filter = filter
        searcher.PropertiesToLoad.Add("userAccountControl")
        searcher.PropertiesToLoad.Add("mail")
        searcher.PropertiesToLoad.Add("givenName")
        searcher.PropertiesToLoad.Add("SN")
        searcher.PropertiesToLoad.Add("cn")
        'searcher.PropertiesToLoad.Add("title")
        Dim Results As System.DirectoryServices.SearchResult = searcher.FindOne
        If Not IsNothing(Results) Then
            Try
                Const ADS_UF_ACCOUNTDISABLE As Integer = &H2
                Dim dummy As Integer = CInt(Results.GetDirectoryEntry.Properties("userAccountControl").Value)

                If CBool(dummy And ADS_UF_ACCOUNTDISABLE) Then Return False
            Catch ex As Exception
                Return False
            End Try
            'If Results.Properties("mail").Count = 1 Then End If
        End If
        Return Not (Results Is Nothing)
    End Function

    ' called by StrandedUsers action of EditSetup
    Function CheckADUser(u)
        ' returns true if user exists, false if not found
        '   u = "VHA12\VHAMADTESTU"
        ' polls the domain portion of "u"

        Dim sDomain, sUser, bExists
        Dim oNetwork, oUser
        Dim aDU
        bExists = False

        aDU = Split(u & "\zzz\zzz", "\")
        sDomain = aDU(0)
        sUser = aDU(1)

        If sDomain <> "None" And sUser <> "None" And sDomain <> "zzz" And sUser <> "zzz" Then
            oNetwork = Vb6.CreateObject("WScript.Network")
            On Error Resume Next
            oUser = GetObject("WinNT://" & sDomain & "/" & sUser & ",user")
            If Err.Number <> 0 Then
                ' match not found
                bExists = False
            Else
                ' WINNT call succeeded, match returned, verify it:
                If UCase(oUser.Name) = UCase(sUser) Then
                    bExists = True
                Else
                    bExists = False
                End If
            End If
            oUser = Nothing
            oNetwork = Nothing
        End If

        CheckADUser = bExists
    End Function

    Private Sub CalculateAndWriteTeamDelays(ByVal iTeam As Integer)
        Dim cntZeroDay, cntOneDay, cntTwoDays, cntThreeDays
        Dim perZeroDay, perOneDay, perTwoDays, perThreeDays
        Dim cntMore, cntTotal, MaxDelay
        Dim perMore, perTotal, thisDelay, lastIndex
        Dim form_StartDate, form_EndDate, selectName

        form_StartDate = Request.Form("form_StartDate")
        form_EndDate = Request.Form("form_EndDate")
        form_CheckSuppressDetails = Request.Form("form_SuppressDetails")

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        cntZeroDay = 0
        cntOneDay = 0
        cntTwoDays = 0
        cntThreeDays = 0
        cntMore = 0
        cntTotal = 0
        MaxDelay = 0

        ' FOR LOOPS TO BUILD COUNTS
        sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_LocationIndex, tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Reason," & " tab_Audit.Au_IndexMessage, tab_Messages.Msg_LastName," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm, tab_Audit.Au_Username" & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index"
        ' #date# for access, 'date' for sSqlString
        If _clsMessageVAR.BUsesSqlString = True Then
            sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= '" & form_StartDate & "' AND tab_Messages.Msg_Dt <= '" & form_EndDate & "'"
        Else
            sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= #" & form_StartDate & "# AND tab_Messages.Msg_Dt <= #" & form_EndDate & "#"
        End If

        sSqlString = sSqlString & " AND tab_Audit.Au_Action = 'Completed' AND tab_Messages.Msg_SiteNum = '" & S & "'"

        sSqlString = sSqlString & " AND tab_Messages.Msg_TeamIndex = " & iTeam
        selectName = "Team: " & Me.GetTeamName(iTeam)

        ' if multiple "Completed" audits, then put the first completion first
        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt ASC, tab_Audit.Au_Tm ASC;"

        If _clsMessageVAR.BDebug = True Then
            Response.Write("sSqlString=" & sSqlString & "<br>")
        End If

        'On Error Resume Next

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                Response_WriteLine("<p>No Messages found for team " & selectName & " and date range specified.</p>")
            Else
                ' lastIndex would be the same if Audit has multiple "tab_Audit.Au_Action=Completed" entries
                lastIndex = 0
                While sqlDataReader.Read = True
                    If lastIndex = sqlDataReader.Item("Msg_Index") Then
                        ' same message, skip it:
                        'Response.Write("skipping " & sqlDataReader.Item("Msg_Index") & ", it has multiple Completions<br>")
                    Else
                        ' new message, check it:
                        lastIndex = sqlDataReader.Item("Msg_Index")

                        ' returns integer WeekDays
                        thisDelay = Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "Weekdays")

                        If thisDelay = 0 Then
                            cntZeroDay = cntZeroDay + 1
                        End If
                        If thisDelay = 1 Then
                            cntOneDay = cntOneDay + 1
                        End If
                        If thisDelay = 2 Then
                            cntTwoDays = cntTwoDays + 1
                        End If
                        If thisDelay = 3 Then
                            cntThreeDays = cntThreeDays + 1
                        End If
                        If thisDelay > 3 Then
                            cntMore = cntMore + 1
                        End If
                        If thisDelay > MaxDelay Then
                            MaxDelay = thisDelay
                        End If
                        cntTotal = cntTotal + 1
                    End If
                End While

                If cntZeroDay = 0 Then
                    perZeroDay = 0
                Else
                    perZeroDay = 100 * cntZeroDay / cntTotal
                End If
                If cntOneDay = 0 Then
                    perOneDay = 0
                Else
                    perOneDay = 100 * cntOneDay / cntTotal
                End If
                If cntTwoDays = 0 Then
                    perTwoDays = 0
                Else
                    perTwoDays = 100 * cntTwoDays / cntTotal
                End If
                If cntThreeDays = 0 Then
                    perThreeDays = 0
                Else
                    perThreeDays = 100 * cntThreeDays / cntTotal
                End If
                If cntMore = 0 Then
                    perMore = 0
                Else
                    perMore = 100 * cntMore / cntTotal
                End If
                If cntTotal = 0 Then
                    perTotal = 0
                Else
                    perTotal = 100 * cntTotal / cntTotal
                End If

                Response_WriteLine("<p><table border=""1"" cellspacing=""0"" style=""width:30%;"">")
                Response_WriteLine("<tr><th colspan=""4"">Completion Rate In Weekdays for Closed Messages (Individual)</th></tr>")
                Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">" & selectName & "</th></tr>")
                Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">Range: " & form_StartDate & "-" & form_EndDate & "</th></tr></table>")
                Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"" style=""width:30%;""><tr><th>&nbsp;&nbsp;Time</th><th>&nbsp;&nbsp;Count</th><th align=""right"">&nbsp;&nbsp;&nbsp;%</th><th>Cumul.%</th></tr>")
                Response_WriteLine("<tr><td>0 days</td><td align=""right"">" & cntZeroDay & "</td><td align=""right"">" & Me.roundit(perZeroDay, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay, 0) & "%</td></tr>")
                Response_WriteLine("<tr><td>1 day</td><td align=""right"">" & cntOneDay & "</td><td align=""right"">" & Me.roundit(perOneDay, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay, 0) & "%</td></tr>")
                Response_WriteLine("<tr><td>2 days</td><td align=""right"">" & cntTwoDays & "</td><td align=""right"">" & Me.roundit(perTwoDays, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay + perTwoDays, 0) & "%</td></tr>")
                Response_WriteLine("<tr><td>3 days</td><td align=""right"">" & cntThreeDays & "</td><td align=""right"">" & Me.roundit(perThreeDays, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay + perTwoDays + perThreeDays, 0) & "%</td></tr>")
                Response_WriteLine("<tr><td>&gt; 3 days</td><td align=""right"">" & cntMore & "</td><td align=""right"">" & Me.roundit(perMore, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay + perTwoDays + perThreeDays + perMore, 0) & "%</td></tr>")
                Response_WriteLine("<tr><td>&nbsp;</td><td align=""right"">" & cntTotal & "</td><td align=""right"">" & Me.roundit(perTotal, 0) & "%</td><td>&nbsp;</td></tr>")
                Response_WriteLine("<tr><td>Greatest Delay</td><td align=""right"">" & Me.roundit(MaxDelay, 1) & "</td><td>Days</td><td>&nbsp;</td></tr>")
                Response_WriteLine("</table></p>")

                'Response_WriteLine("<p><table><tr><td colspan=""4""><b>Messages Completed After 2 Day Deadline</b></td></tr>")
                'Response_WriteLine("<tr><td><b>Patient</b></td><td><b>Date</b></td><td>Reason</td><td>Index</td></tr>")
                'Response_WriteLine("" & LongDelayList & "")
                'Response_WriteLine("</table></p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Sub

    Private Function ADGroupExists(ByVal sGroup As String)
        Dim adRoot As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry("GC://" & _clsMessageVAR.DCPath.ToString())
        Using searcher As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(adRoot)
            searcher.SearchScope = SearchScope.Subtree
            searcher.Filter = "cn=" & sGroup
            'searcher.PropertiesToLoad.Add("distinguishedname")
            'searcher.PropertiesToLoad.Add("displayname")
            searcher.PropertiesToLoad.Add("cn")

            Using results As SearchResultCollection = searcher.FindAll()
                For Each group As SearchResult In results
                    If sGroup = group.Properties("cn")(0).ToString() Then Return True
                Next
            End Using
        End Using

        Return False ' Not found in Active Directory

    End Function

    ' called by CheckAdmin()
    Private Function GetADUserGroups()
        Dim strGroups As String = ""
        Dim Array(2) As String

        Array = Split(Page.User.Identity.Name, "\")

        Dim adRoot As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry("GC://" & _clsMessageVAR.DCPath.ToString())
        Using searcher As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(adRoot)
            searcher.SearchScope = SearchScope.Subtree
            searcher.Filter = "(&(ObjectClass=User)(SAMAccountName=" & Array(1) & "))"
            searcher.PropertiesToLoad.Add("MemberOf")

            Using results As SearchResultCollection = searcher.FindAll()
                If results.Count > 0 Then
                    Dim group As New DirectoryEntry(results(0).Path)
                    For Each member As Object In group.Properties("MemberOf")
                        member = member.Substring(0, member.IndexOf(",", 0))
                        strGroups = member.Replace("CN=", "") & "," & strGroups
                    Next
                Else
                    GetADUserGroups = strGroups
                End If
            End Using
            GetADUserGroups = strGroups
        End Using
    End Function

    Function InsertTableRecord(s As String)

        Dim strConn As String

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = s

        InsertTableRecord = False

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            If (MyCommand.ExecuteNonQuery().Equals(1)) Then
                '  Successfully inserted record
                InsertTableRecord = True
            Else
                System.Web.HttpContext.Current.Session(“Oops”) = "*** Error Inserting - " & s & " *** "
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Sub UpdateTableRecord(s As String)

        Dim strConn As String

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = s

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            If (MyCommand.ExecuteNonQuery().Equals(1)) Then
                '  Successfully updated record
            Else
                System.Web.HttpContext.Current.Session(“Oops”) = "*** Error Updating - " & s & " *** "
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Sub

    Function UpdateTableRecords(s As String)

        Dim strConn As String

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = s

        UpdateTableRecords = False

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            If (MyCommand.ExecuteNonQuery().Equals(0)) Then
                System.Web.HttpContext.Current.Session(“Oops”) = "*** Error Updating - " & s & " *** "
            Else
                '  Successfully updated
                UpdateTableRecords = True
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Function DeleteTableRecord(s As String)

        Dim strConn As String

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = s

        DeleteTableRecord = False

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            If (MyCommand.ExecuteNonQuery().Equals(1)) Then
                '  Successfully deleted record
                DeleteTableRecord = True
            Else
                System.Web.HttpContext.Current.Session(“Oops”) = "*** Error Deleting - " & s & " *** "
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Function DeleteTableRecords(s As String)

        Dim strConn As String

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = s

        DeleteTableRecords = False

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            If (MyCommand.ExecuteNonQuery().Equals(0)) Then
                '  Failure - Nothing deleted
                System.Web.HttpContext.Current.Session(“Oops”) = "*** Error Deleting - " & s & " *** "
            Else
                DeleteTableRecords = True
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Function

    Sub CheckAdmin()

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        ' If can, Sets variables {AdminAccess, AdminSite, AdminLocation, AdminTeam, AdminType, UserSID, S, SiteName}
        ' only called when (A = "Admin" or A = "Setup")
        '
        ' AdminAccess is a global
        '   AdminAccess = 0 upon entry
        '	  ="Admin" if in Admins table with value of 000
        '	  ="Admin" if in Admins table with value of one site (537,607,etc) and tab_Admins.Adm_AccessLevel = "Admin"
        '		  **** Admin for Entire System is allowed
        '
        '	  ="Site" if in Admins table with value of one site (537,607,etc - not 000) and tab_Admins.Adm_AccessLevel = "Site"
        '		 **** multiple sites OK
        '		 **** Site for Entire system is allowed
        '
        '	  ="Member" if not in Admins table, but instead in tab_Teams
        '		 **** if a Member is also in Admins table, gets AdminAccess="Site,Admin" level access first
        '			  and then doesn't check for Member level
        '		 **** but "Consistency Check" will show a Warning for this situation.
        '
        ' AdminSite is a global
        '  AdminSite = "None" upon entry
        '    ="000" if tab_Admins.Adm_AccessLevel = 'Admin'
        '    ="xxx" (the 3 digit site code) if tab_Admins.Adm_AccessLevel = 'Site'
        '
        ' AdminLocation is a global
        '  AdminLocation = 0 upon entry
        '    =tab_Locations.Lo_Index for this member
        '    =-1 multiple Locations for member
        '
        ' AdminTeam is a global
        '  AdminTeam = 0 upon entry
        '    =tab_Teams.Te_Index for this member
        '    =-1 if multiple Teams for member
        '
        ' AdminType = the Type has access to:
        '	"None" = initialized
        '	if in Admins table, reference tab_Admins.Adm_Type:
        '		= {All, PACT, FEE, ... etc}
        '	else if in Members table:
        '		= value of last tab_Locations.Lo_Type
        '
        ' UserSID = the AD hex-to-string coded SID value unique to the username
        '   "" = not yet loaded
        '   "0105000000000005150000000352E2686E63F614E669446E6D050000" = exmple value
        '   if AD's SID matches Admin or Members table SID value, then access is granted
        '   else no access
        '
        ' S is a global
        '  S="" or  already upon entry
        '    =xxx (the 3 digit site code) if can predict it uniquely
        ' SiteName
        '    =tab_Sites.Si_Name - if member of 1 Site where can uniquely pick it

        Dim sSqlString, provCount, sGroupNames, sGroup
        Dim sSites As String = ""

        If _clsMessageVAR.BDebug Then
            Response.Write("In CheckAdmin() Beginning:<br>")
            Response.Write(" - AdminAccess = " & AdminAccess & ".<br>")
            Response.Write(" - AdminSite = " & AdminSite & ".<br>")
            Response.Write(" - AdminType = " & AdminType & ".<br>")
            Response.Write(" - UserSID = " & UserSID & ".<br>")
        End If


        ' UserSID will be "" at this point
        ' returns the SID for logged in user
        '   from Application Variable if it was cached already
        '   or from AD if not cached already
        ' or returns "NOTFOUND" or "DCERROR"
        Me.UserSID = PollADforSID()

        'Response.Write(" - UserSID = " & UserSID & ".<br>")

        ' ADMINS LOOKUP
        ' determine the sSqlString lookup string
        ' ordering in this order: {Site, Admin} so last level to grant is "Admin", and last SiteNum is "000"
        sSqlString = "SELECT * FROM tab_Admins"
        Select Case Me.UserSID
            Case "DCERROR"
                ' AD issues
                ' lookup user access based one only the Username, not the SID
                sSqlString = sSqlString & " WHERE tab_Admins.Adm_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'"
            Case "NOTFOUND"
                ' AD lookup successful but not found in AD.  User in OU that is unreadable by the service account?
                ' lookup user access based on only the Username, not the SID
                sSqlString = sSqlString & " WHERE tab_Admins.Adm_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'"
            Case Else
                ' GOOD, SID found, lookup user access based on Username and SID
                sSqlString = sSqlString & " WHERE tab_Admins.Adm_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " AND tab_Admins.Adm_SID = '" & Me.UserSID & "'"
        End Select
        sSqlString = sSqlString & " ORDER BY tab_Admins.Adm_AccessLevel DESC, tab_Admins.Adm_SiteNum DESC;"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                ' not in Admins table, so
                ' AdminAccess = "None" still
                ' AdminSite = "None" still
                ' AdminType = "None" still
            Else
                sqlDataReader.Read()
                Me.AdminAccess = sqlDataReader.Item("Adm_AccessLevel")
                Me.AdminSite = sqlDataReader.Item("Adm_SiteNum")
                Me.AdminType = sqlDataReader.Item("Adm_Type")
                Me.AdminSites = sqlDataReader.Item("Adm_Sites")

                If Me.AdminSite <> "000" Then
                    ' can predict the site
                    S = Me.AdminSite
                Else
                    ' cannot predict, it's a System-wide Admin (tab_Admins.Adm_AccessLevel = Admin, SiteNum=000)
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        If _clsMessageVAR.BDebug Then
            Response.Write("In CheckAdmin() After Admin table lookup:<br>")
            Response.Write(" - AdminAccess = " & AdminAccess & ".<br>")
            Response.Write(" - AdminSite = " & AdminSite & ".<br>")
            Response.Write(" - AdminType = " & AdminType & ".<br>")
            Response.Write(" - UserSID = " & UserSID & ".<br>")
        End If

        ' MEMBERS lookup
        ' Username not found in Admins table, check Members table (AdminAccess is not found to be "Admin" or "Site")
        If Me.AdminAccess = "None" Then
            ' not admin, check for tab_Teams access.  If so,  AdminAccess = "Member".
            ' if member has only 1 Location, then  the SiteName to that.
            ' ^^ beware that if member chooses different site it "ignores" it.

            provCount = 0
            ' if member  to Inactive - don't let in.

            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_LocationIndex, tab_Locations.Lo_Type, tab_Locations.Lo_SiteNum" & " FROM (tab_Teams INNER JOIN tab_Members ON tab_Teams.Te_Index = tab_Members.Me_TeamIndex)" & " INNER JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index"
            ' determine the sSqlString lookup string
            ' ordering in this order: {Site, Admin} so last level to grant is "Admin", and last SiteNum is "000"
            Select Case Me.UserSID
                Case "DCERROR"
                    ' AD issues are common
                    ' lookup user access based one only the Username, not the SID
                    sSqlString = sSqlString & " WHERE tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'"
                Case "NOTFOUND"
                    ' AD lookup successful but not found in AD.  User in OU that is unreadable by the service account?
                    ' lookup user access based on only the username, not the SID
                    sSqlString = sSqlString & " WHERE tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'"
                Case Else
                    ' GOOD, SID found, lookup user access based on SID
                    ' ************** REMOVE THE "OR SID IS NULL" line after all SIDS are active! ******************
                    ' ******* 11-29-2012: during conversion period, allow NULL SID to just match a username *******
                    sSqlString = sSqlString & " WHERE tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " AND tab_Members.Me_SID = '" & Me.UserSID & "'"
            End Select
            ' require Active members for login access
            sSqlString = sSqlString & " AND tab_Members.Me_Active = 'Yes'" & " ORDER BY tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Members.Me_SortOrder;"

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    ' AdminAccess = "None" still
                    ' AdminSite = "None" still
                    ' AdminType = "None" still
                Else
                    While sqlDataReader.Read = True
                        provCount = provCount + 1
                        Me.AdminAccess = "Member"
                        ' AdminSite, AdminTeam, AdminType are  to the last ones in the sort order
                        Me.AdminLocation = sqlDataReader.Item("Te_LocationIndex")
                        Me.AdminTeam = sqlDataReader.Item("Te_Index")
                        Me.AdminType = sqlDataReader.Item("Lo_Type")
                        sSites = sSites + "'" + sqlDataReader.Item("Lo_SiteNum") + "', "
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("provCount=" & provCount & "<br>")
                            Response.Write("AdminLocation=" & AdminLocation & "<br>")
                            Response.Write("AdminTeam=" & AdminTeam & "<br><br>")
                            Response.Write("AdminType=" & AdminType & "<br><br>")
                        End If
                    End While
                    Me.AdminSites = sSites.Remove(sSites.LastIndexOf(", "))
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

            If _clsMessageVAR.BDebug = True Then
                Response.Write("provCount=" & provCount & "<br>")
            End If

            If provCount > 0 Then
                ' can predict the site
                ' tab_Locations.Lo_Index is a Number

                MyCommand.CommandText = "SELECT tab_Locations.Lo_SiteNum FROM tab_Locations WHERE tab_Locations.Lo_Index = " & Me.AdminLocation & ";"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = False Then
                        ' Nothing found TODO - Do we need a handler?
                    Else
                        S = sqlDataReader.Item("Lo_SiteNum")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                If provCount = 1 Then
                    ' above SiteName setting catches it.
                Else
                    ' ISSUES:
                    ' *** Members that have multiple Locations
                    ' AdminSite is the last one in the list
                    ' AdminTeam is the last one in the list			
                    ' *** so allow AdminSite to default to the last LocationIndex it was  to - ordered by tab_Members.Me_SortOrder
                    ' *** they can pick a new one if they need
                    ' *** AdminSite = -1
                    ' reset AdminLocation to -1 for multiple Locations
                    Me.AdminLocation = -1
                    ' reset AdminTeam to -1 for multiple Teams
                    Me.AdminTeam = -1
                    If Me.JustToTheFirstSpace(Me.killChars(Request.QueryString("S").ToString())) <> "" Then S = Me.JustToTheFirstSpace(Me.killChars(Request.QueryString("S").ToString()))
                End If
            Else
                ' here provCount = 0 still
                ' this happens if user isn't in members or admins table, but clicked Admin Menu
                ' at this point, AdminSite = 0 still.
            End If

            If _clsMessageVAR.BDebug Then
                Response.Write("In CheckAdmin() After Member table lookup:<br>")
                Response.Write(" - AdminAccess = " & AdminAccess & ".<br>")
                Response.Write(" - AdminSite = " & AdminSite & ".<br>")
                Response.Write(" - AdminType = " & AdminType & ".<br>")
                Response.Write(" - AdminSites = " & AdminSites & ".<br>")
                Response.Write(" - UserSID = " & UserSID & ".<br>")
            End If
        End If ' AdminAccess = "None"



        ' AD GROUPS lookup
        ' if still no access level, resort to AD group memberships
        If Me.AdminAccess = "None" Then
            ' Check NT Group memberships to see if in a "Clerks" group.
            ' Database membership is given priority, thus checking AD groups is last option
            ' tab_ADGroups
            '	.AD_SiteNum = {607, 695, etc) TEXT 255
            '	.AD_GroupName = "VHAMAD MM Clerks"  ' sample
            '	.AD_AccessLevel = {Site}

            ' sGroupNames will be of format {Group Name 1, Group 2, Group 3,}
            sGroupNames = Me.GetADUserGroups()
            If _clsMessageVAR.BDebug = True Then
                Response.Write("sGroupNames=" & sGroupNames & "<br>")
            End If
            sGroupNames = UCase(sGroupNames)

            If sGroupNames = "" Then
                ' none, skip group checking
            Else
                ' loop through groups from the table

                MyCommand.CommandText = "SELECT tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_GroupName, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_Type, tab_ADGroups.AD_Sites" & " FROM tab_ADGroups ORDER BY tab_ADGroups.AD_GroupName DESC;"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Not sqlDataReader.HasRows Then
                        ' Nothing found TODO - Do we need a handler?
                    Else
                        While sqlDataReader.Read = True
                            If IsDBNull(sqlDataReader.Item("AD_GroupName")) Then
                                sGroup = ","
                            Else
                                sGroup = UCase(sqlDataReader.Item("AD_GroupName")) & ","
                            End If

                            If InStr(sGroupNames, sGroup) Then
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sGroup=" & sGroup & "<br>")
                                End If

                                ' found
                                ' Priority order:  Admin, Site
                                ' note that the last site in the sort order wins the default site.
                                ' it's up to the Group Owner not to have people in mutiple site groups

                                '			NEW	Site607	Site000	Admn607	Admn000
                                'EXISTING				
                                'nothing		upgrade	upgrade	upgrade	upgrade
                                'Site607		..repl. upgrade	upgrade	upgrade (site manager)
                                'Site000		nothing	..same.	upgrade	upgrade (system manager)
                                'Admn607		nothing	nothing	..same.	upgrade (site admin)
                                'Admn000		nothing	nothing	nothing	..same. (system admin)

                                ' Compare EXISTING access level
                                Select Case Me.AdminAccess

                                    Case "None"
                                        Me.AdminSite = sqlDataReader.Item("AD_SiteNum")
                                        Me.AdminAccess = sqlDataReader.Item("AD_AccessLevel")
                                        Me.AdminType = sqlDataReader.Item("AD_Type")
                                        Me.AdminSites = sqlDataReader.Item("AD_Sites")

                                    Case "Site"
                                        If Me.AdminSite = "000" Then
                                            If sqlDataReader.Item("AD_AccessLevel") = "Admin" Then
                                                Me.AdminSite = sqlDataReader.Item("AD_SiteNum")
                                                Me.AdminAccess = sqlDataReader.Item("AD_AccessLevel")
                                                Me.AdminType = sqlDataReader.Item("AD_Type")
                                                Me.AdminSites = sqlDataReader.Item("AD_Sites")
                                            End If
                                        Else
                                            If sqlDataReader.Item("AD_AccessLevel") = "Site" Or sqlDataReader.Item("AD_AccessLevel") = "Admin" Then
                                                Me.AdminSite = sqlDataReader.Item("AD_SiteNum")
                                                Me.AdminAccess = sqlDataReader.Item("AD_AccessLevel")
                                                Me.AdminType = sqlDataReader.Item("AD_Type")
                                                Me.AdminSites = sqlDataReader.Item("AD_Sites")
                                            End If
                                        End If

                                    Case "Admin"
                                        If Me.AdminSite = "000" Then
                                            ' top already, don't demote
                                        Else
                                            If sqlDataReader.Item("AD_AccessLevel") = "Admin" Then
                                                Me.AdminSite = sqlDataReader.Item("AD_SiteNum")
                                                Me.AdminAccess = sqlDataReader.Item("AD_AccessLevel")
                                                Me.AdminType = sqlDataReader.Item("AD_Type")
                                                Me.AdminSites = sqlDataReader.Item("AD_Sites")
                                            End If
                                        End If
                                        Response.Write("huh1<br>")
                                    Case Else
                                        Me.ErrorHandler("Got to ELSE statement in CheckAdmin() with user " & Me.UserName & ".", False, False)

                                End Select
                            End If ' InStr
                        End While
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                If Me.AdminAccess <> "None" Then
                    ' level changed, see if S can be predicted	
                    If Me.AdminSite = "000" Then
                        ' for all sites.  Do not alter choice of S
                    Else
                        ' AdminSite for single SiteNum, can predict it
                        ' can predict the site
                        S = Me.AdminSite
                    End If
                End If

            End If ' sGroupNames = ""
        End If ' AdminAccess="None"


        '  the default SiteName based on passed through or predicted S
        MyCommand.CommandText = "SELECT tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & S & "';"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                Me.SiteName = ""
            Else
                If IsDBNull(sqlDataReader.Item("Si_Name")) Then
                    Me.SiteName = ""
                Else
                    Me.SiteName = sqlDataReader.Item("Si_Name")
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        If _clsMessageVAR.BDebug Then
            Response.Write("In CheckAdmin() End.  After Group lookup:<br>")
            Response.Write(" - AdminAccess = " & AdminAccess & ".<br>")
            Response.Write(" - AdminSite = " & AdminSite & ".<br>")
            Response.Write(" - AdminType = " & AdminType & ".<br>")
            Response.Write(" - AdminSites = " & AdminSites & ".<br>")
            Response.Write(" - UserSID = " & UserSID & ".<br>")
        End If
    End Sub

    Function DoesMemberSiteMatchMessageSite(SSI)
        If _clsMessageVAR.BDebug = True Then
            Response.Write("AdminSite=" & AdminSite & "<br>")
            Response.Write("AdminLocation=" & AdminLocation & "<br>")
        End If
        Dim bOK, sSqlString, MessageSiteNum


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        bOK = False

        ' most common:  member is from this Location, save database lookup
        If Me.AdminLocation = SSI Then
            bOK = True
        Else
            ' loop through all teams for this member and see if 1 is a match
            MessageSiteNum = Me.GetSiteNum(SSI)

            sSqlString = "SELECT tab_Locations.Lo_SiteNum, tab_Members.Me_Index" & " FROM (tab_Locations INNER JOIN tab_Teams ON tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex)" & " INNER JOIN tab_Members ON tab_Teams.Te_Index = tab_Members.Me_TeamIndex" & " WHERE tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "';"

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                While sqlDataReader.Read = True
                    If sqlDataReader.Item("Lo_SiteNum") = MessageSiteNum Then
                        bOK = True
                    End If
                End While

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
        DoesMemberSiteMatchMessageSite = bOK
    End Function

    Function GetSiteName(i)
        ' i = tab_Sites.Si_SiteNum = tab_Locations.Lo_SiteNum

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If Not IsNothing(i) Then
            If i.ToString = "" Or IsDBNull(i) Then
                GetSiteName = ""
            Else

                MyCommand.CommandText = "SELECT tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & i & "';"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Not sqlDataReader.HasRows Then
                        System.Web.HttpContext.Current.Session(“Oops”) = "*** ERROR in GetSiteName() - The likely reason is 'i' is NULL ***"
                    Else
                        sqlDataReader.Read()

                        If IsDBNull(sqlDataReader.Item("Si_Name")) Then
                            GetSiteName = ""
                        Else
                            GetSiteName = sqlDataReader.Item("Si_Name")
                        End If
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try
            End If
        Else
            GetSiteName = ""
        End If

    End Function

    Function GetSiteNum(i)
        ' i = tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex
        Dim sSqlString, r


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If i = 0 Or IsDBNull(i) Then
            GetSiteNum = ""
        Else
            sSqlString = "SELECT tab_Locations.Lo_SiteNum FROM tab_Locations WHERE tab_Locations.Lo_Index = " & i & ";"
            'On Error Resume Next

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetSiteNum = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = True Then
                        If IsDBNull(sqlDataReader.Item("Lo_SiteNum")) Then
                            GetSiteNum = ""
                        Else
                            GetSiteNum = sqlDataReader.Item("Lo_SiteNum")
                        End If
                    Else
                        GetSiteNum = ""
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetLocationName(i)
        ' i = tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex

        GetLocationName = ""

        If i = 0 Or IsDBNull(i) Then
            GetLocationName = ""
        Else
            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = "SELECT tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_Index = " & i & ";"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    ' System.Web.HttpContext.Current.Session(“Oops”) = "*** ERROR in GetLocationName() - The likely reason is 'i' is NULL ***"
                    GetLocationName = ""
                Else
                    sqlDataReader.Read()

                    If IsDBNull(sqlDataReader.Item("Lo_Name")) Then
                        GetLocationName = ""
                    Else
                        GetLocationName = sqlDataReader.Item("Lo_Name")
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If
    End Function

    Function GetLocationIndex(i)
        ' i = tab_Teams.Te_Index
        Dim sSqlString


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        GetLocationIndex = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetLocationIndex = ""
        Else
            sSqlString = "SELECT tab_Teams.Te_LocationIndex FROM tab_Teams WHERE tab_Teams.Te_Index = " & i & ";"
            'On Error Resume Next

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetLocationIndex = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetLocationIndex = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Te_LocationIndex")) Then
                            GetLocationIndex = ""
                        Else
                            GetLocationIndex = sqlDataReader.Item("Te_LocationIndex")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetTeamIndex(i)
        ' i = tab_Members.Me_Index
        Dim sSqlString


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        GetTeamIndex = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetTeamIndex = ""
        Else
            sSqlString = "SELECT tab_Members.Me_TeamIndex FROM tab_Members WHERE tab_Members.Me_Index = " & i & ";"
            'On Error Resume Next

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetTeamIndex = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetTeamIndex = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Me_TeamIndex")) Then
                            GetTeamIndex = ""
                        Else
                            GetTeamIndex = sqlDataReader.Item("Me_TeamIndex")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetTeamName(i)
        ' i = tab_Teams.Te_Index = tab_Members.Me_TeamIndex

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = "SELECT tab_Teams.Te_Name FROM tab_Teams WHERE tab_Teams.Te_Index = " & i & ";"

        If i = 0 Or IsDBNull(i) Then
            GetTeamName = ""
        Else
            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    GetTeamName = ""
                Else
                    sqlDataReader.Read()

                    If IsDBNull(sqlDataReader.Item("Te_Name")) Then
                        GetTeamName = ""
                    Else
                        GetTeamName = sqlDataReader.Item("Te_Name")
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function IsTeamActive(i)
        ' i = tab_Teams.Te_Index
        Dim sSqlString


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        IsTeamActive = ""

        If i = 0 Or IsDBNull(i) Then
            IsTeamActive = ""
        Else
            sSqlString = "SELECT tab_Teams.Te_Active FROM tab_Teams WHERE tab_Teams.Te_Index = " & i & ";"
            'On Error Resume Next

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    IsTeamActive = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        IsTeamActive = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Te_Active")) Then
                            IsTeamActive = ""
                        Else
                            IsTeamActive = sqlDataReader.Item("Te_Active")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetTeamListFromUsername(u)
        ' u = Username in the form of DOMAIN\USERNAME
        ' return CSV list of "sitename: teamname" e.j. "Rockford: Red 2"

        Dim sSqlString, str
        sSqlString = "SELECT tab_Teams.Te_Name, tab_Locations.Lo_Name" & " FROM (tab_Teams INNER JOIN tab_Members ON tab_Teams.Te_Index = tab_Members.Me_TeamIndex)" & " INNER JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Members.Me_Username LIKE '" & u & "'" & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
        'On Error Resume Next


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            'If Err.Number <> 0 Then
            'Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>Unable to GetTeamListFromUsername<br>", False, False)
            'End If
            'On Error GoTo 0

            str = ""

            While sqlDataReader.Read = True
                If str = "" Then
                    If Not IsDBNull(sqlDataReader.Item("Lo_Name")) Then
                        str = sqlDataReader.Item("Lo_Name")
                    End If
                    If Not IsDBNull(sqlDataReader.Item("Te_Name")) Then
                        str = str & ": " & sqlDataReader.Item("Te_Name")
                    End If
                Else
                    If IsDBNull(sqlDataReader.Item("Lo_Name")) Then
                        str = str & ", "
                    Else
                        str = str & ", " & sqlDataReader.Item("Lo_Name")
                    End If
                    If Not IsDBNull(sqlDataReader.Item("Te_Name")) Then
                        str = str & ": " & sqlDataReader.Item("Te_Name")
                    End If
                End If
            End While

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        GetTeamListFromUsername = str
    End Function

    Function CleanUserName(u)
        ' u = Username in the form of DOMAIN\USERNAME
        ' return the right portion
        Dim arrU
        If InStr(u, "\") Then
            arrU = Split(u & "\zzz", "\")
            If arrU(1) <> "zzz" Then
                CleanUserName = arrU(1)
            Else
                CleanUserName = u
            End If
        Else
            CleanUserName = u
        End If
    End Function

    Function isUserNameOnTeam(u, ti)
        'isUserNameOnTeam(form_AssignTo, rsTeamIndex)
        ' verify member exists on team and is active, return true
        ' not on team or inactive, return false
        Dim sSqlString

        isUserNameOnTeam = False

        If u = "" Or IsDBNull(u) Or ti = 0 Or IsDBNull(ti) Then
            ' return false to indicate failure to find
            isUserNameOnTeam = False
        Else
            sSqlString = "SELECT tab_Members.Me_Name FROM tab_Members WHERE tab_Members.Me_Username LIKE '" & u & "' AND tab_Members.Me_TeamIndex = " & ti & " AND tab_Members.Me_Active = 'Yes';"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    ' return "" to indicate failure to find
                    isUserNameOnTeam = False
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        ' return "" to indicate failure to find
                        isUserNameOnTeam = False
                    Else
                        ' early on Title was an optional field so some may be NULL
                        If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                            ' return "" to indicate failure to find
                            isUserNameOnTeam = False
                        Else
                            isUserNameOnTeam = True
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetMemberNameFlaggedUandTI(u, ti)
        ' u = tab_Members.Me_Username
        ' ti = tab_Members.Me_TeamIndex
        ' this can be a slow lookup when it's looped so skip if server is slow
        ' if not slow, return "Last, First Title"
        ' if slow, return u
        ' if nothing found, return ""
        Dim sec
        GetMemberNameFlaggedUandTI = ""
        ' seconds.  if timeouts in last 1 minute then don't call the  Me.UserName  lookup
        sec = Me.SecSinceOverload()
        If sec >= 0 And sec < 60 Then
            GetMemberNameFlaggedUandTI = Me.CleanUserName(u) & " - " & PollMemberNameForLogin(u)
        Else
            Dim sSqlString
            If u = "" Or IsDBNull(u) Or IsDBNull(ti) Then
                ' return "" to indicate failure to find
                GetMemberNameFlaggedUandTI = ""
            Else
                sSqlString = "SELECT tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members WHERE tab_Members.Me_Username LIKE '" & u & "' AND tab_Members.Me_TeamIndex = " & ti & " ORDER BY tab_Members.Me_Active DESC;"
                'On Error Resume Next


                Dim strConn As String
                Dim sqlDataReader As SqlDataReader = Nothing

                strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

                Dim MyConnection = New SqlConnection(strConn)
                Dim MyCommand As New SqlCommand()
                MyCommand.Connection = MyConnection
                MyCommand.CommandType = CommandType.Text

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Err.Number <> 0 Then
                        ' return "" to indicate failure to find
                        GetMemberNameFlaggedUandTI = ""
                    Else
                        'On Error GoTo 0
                        If sqlDataReader.Read = False Then
                            ' return "" to indicate failure to find
                            GetMemberNameFlaggedUandTI = ""
                        Else
                            ' early on Title was an optional field so some may be NULL
                            If IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                    ' return "" to indicate failure to find
                                    GetMemberNameFlaggedUandTI = ""
                                Else
                                    GetMemberNameFlaggedUandTI = sqlDataReader.Item("Me_Name") & " - " & PollMemberNameForLogin(sqlDataReader.Item("Me_Name"))
                                End If
                            Else
                                If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                    GetMemberNameFlaggedUandTI = Me.CleanUserName(u) & " " & sqlDataReader.Item("Me_Title") & " - " & PollMemberNameForLogin(u)
                                Else
                                    GetMemberNameFlaggedUandTI = sqlDataReader.Item("Me_Name") & " " & sqlDataReader.Item("Me_Title")
                                End If
                            End If
                        End If
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

            End If
        End If ' 0 <= sec < 60
    End Function

    Function GetMemberNameFromUandTI(u, ti)
        ' u = tab_Members.Me_Username
        ' ti = tab_Members.Me_TeamIndex
        ' this can be a slow lookup when it's looped so skip if server is slow
        ' if not slow, return "Last, First Title"
        ' if slow, return u
        ' if nothing found, return ""
        Dim sec
        GetMemberNameFromUandTI = ""
        ' seconds.  if timeouts in last 1 minute then don't call the  Me.UserName  lookup
        sec = Me.SecSinceOverload()
        If sec >= 0 And sec < 60 Then
            GetMemberNameFromUandTI = Me.CleanUserName(u)
        Else
            Dim sSqlString
            If u = "" Or IsDBNull(u) Or IsDBNull(ti) Then
                ' return "" to indicate failure to find
                GetMemberNameFromUandTI = ""
            Else
                sSqlString = "SELECT tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members WHERE tab_Members.Me_Username LIKE '" & u & "' AND tab_Members.Me_TeamIndex = " & ti & " ORDER BY tab_Members.Me_Active DESC;"
                'On Error Resume Next


                Dim strConn As String
                Dim sqlDataReader As SqlDataReader = Nothing

                strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

                Dim MyConnection = New SqlConnection(strConn)
                Dim MyCommand As New SqlCommand()
                MyCommand.Connection = MyConnection
                MyCommand.CommandType = CommandType.Text

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Err.Number <> 0 Then
                        ' return "" to indicate failure to find
                        GetMemberNameFromUandTI = ""
                    Else
                        'On Error GoTo 0
                        If sqlDataReader.Read = False Then
                            ' return "" to indicate failure to find
                            GetMemberNameFromUandTI = ""
                        Else
                            ' early on Title was an optional field so some may be NULL
                            If IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                    ' return "" to indicate failure to find
                                    GetMemberNameFromUandTI = ""
                                Else
                                    GetMemberNameFromUandTI = sqlDataReader.Item("Me_Name")
                                End If
                            Else
                                If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                    GetMemberNameFromUandTI = Me.CleanUserName(u) & " " & sqlDataReader.Item("Me_Title")
                                Else
                                    GetMemberNameFromUandTI = sqlDataReader.Item("Me_Name") & " " & sqlDataReader.Item("Me_Title")
                                End If
                            End If
                        End If
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

            End If
        End If ' 0 <= sec < 60
    End Function

    Function GetMemberUsername(i)
        ' i = tab_Members.Me_Index
        Dim sSqlString

        GetMemberUsername = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetMemberUsername = ""
        Else
            sSqlString = "SELECT tab_Members.Me_Username FROM tab_Members WHERE tab_Members.Me_Index = " & i & ";"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetMemberUsername = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetMemberUsername = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Me_Username")) Then
                            GetMemberUsername = ""
                        Else
                            GetMemberUsername = sqlDataReader.Item("Me_Username")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetMemberEmail(i)
        ' i = tab_Members.Me_Index
        Dim sSqlString

        GetMemberEmail = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetMemberEmail = ""
        Else
            sSqlString = "SELECT tab_Members.Me_Email FROM tab_Members WHERE tab_Members.Me_Index = " & i & ";"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetMemberEmail = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetMemberEmail = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Me_Email")) Then
                            GetMemberEmail = ""
                        Else
                            GetMemberEmail = sqlDataReader.Item("Me_Email")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetMemberName(i)
        ' i = tab_Members.Me_Index
        Dim sSqlString

        GetMemberName = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetMemberName = ""
        Else
            sSqlString = "SELECT tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members WHERE tab_Members.Me_Index = " & i & ";"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetMemberName = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetMemberName = ""
                    Else
                        ' early on Title was an optional field so some may be NULL
                        If IsDBNull(sqlDataReader.Item("Me_Title")) Then
                            If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                GetMemberName = ""
                            Else
                                GetMemberName = sqlDataReader.Item("Me_Name")
                            End If
                        Else
                            If IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                GetMemberName = sqlDataReader.Item("Me_Title")
                            Else
                                GetMemberName = sqlDataReader.Item("Me_Name") & " " & sqlDataReader.Item("Me_Title")
                            End If
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetTeamMemberNewEmails(i)
        ' return a String list of member emails that are in 
        ' i = tab_Teams.Te_Index = tab_Members.Me_TeamIndex
        ' only those with EmailNew = "Yes"
        Dim str

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        str = ""
        If i = 0 Or IsDBNull(i) Then
            ' skip
        Else
            MyCommand.CommandText = "SELECT tab_Members.Me_Email FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & i & " AND tab_Members.Me_EmailNew = 'Yes'" & " AND tab_Members.Me_Active = 'Yes'" & " ORDER BY tab_Members.Me_SortOrder, tab_Members.Me_Email;"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    GetTeamMemberNewEmails = ""
                Else
                    While sqlDataReader.Read = True
                        If str = "" Then
                            If Not IsDBNull(sqlDataReader.Item("Me_Email")) Then
                                str = sqlDataReader.Item("Me_Email")
                            End If
                        Else
                            If Not IsDBNull(sqlDataReader.Item("Me_Email")) Then
                                str = str & "; " & sqlDataReader.Item("Me_Email")
                            End If
                        End If
                    End While
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
        GetTeamMemberNewEmails = str
    End Function

    Function GetTeamMemberNames(i, ShowHidden, showEditLink)
        ' return a String list of member names that are in 
        ' i = tab_Teams.Te_Index = tab_Members.Me_TeamIndex
        ' only those with ShowOn = "Yes"
        ' Inactive members are shown but include "*" at beginning of name
        '   in case member toggled off but Team name is the same
        '   this is beneficial to the call takers when the caller does not know the member is gone so still references the team the old way
        ' showHidden:
        '   if ShowHidden = true, then include hidden members (tab_Members.Me_ShowOn="No")
        '   if ShowHidden = false, then do not include hidden members (show only tab_Members.Me_ShowOn="Yes")
        ' showEditLink:
        '   if ShowEditLink = true, then add "Edit Member" form link to it
        '   CAN ONLY HAVE THIS if this generated form is not nested within a form

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text
        Dim str

        str = ""
        If i = 0 Or IsDBNull(i) Then
            ' skip
        Else

            MyCommand.CommandText = "SELECT tab_Members.Me_Index, tab_Members.Me_Name, tab_Members.Me_Title, tab_Members.Me_ShowOn, tab_Members.Me_Active FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & i & " ORDER BY tab_Members.Me_SortOrder, tab_Members.Me_Name;"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader
                If Not sqlDataReader.HasRows Then
                    GetTeamMemberNames = ""
                Else
                    While sqlDataReader.Read = True
                        If ShowHidden = True Or sqlDataReader.Item("Me_ShowOn") = "Yes" Then
                            If str = "" Then
                                If Not IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                    If sqlDataReader.Item("Me_Active") = "Yes" Then
                                        str = sqlDataReader.Item("Me_Name")
                                    Else
                                        str = "*" & sqlDataReader.Item("Me_Name")
                                    End If
                                End If
                            Else
                                If Not IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                    If sqlDataReader.Item("Me_Active") = "Yes" Then
                                        str = str & "; " & sqlDataReader.Item("Me_Name")
                                    Else
                                        str = str & "; *" & sqlDataReader.Item("Me_Name")
                                    End If
                                End If
                            End If
                            If Not IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                str = str & " " & sqlDataReader.Item("Me_Title")
                            End If
                        End If
                        If showEditLink = True Then
                            str = str & " <form name=""fMe" & sqlDataReader.Item("Me_Index") & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=Edit"" method=""POST"" style=""margin:0;display:inline;"">" & "<a class=""submitAsLink"" onclick=""fMe" & sqlDataReader.Item("Me_Index") & ".submit()"">" & "<small>Edit</small></a>" & "<input type=""hidden"" name=""form_Choice"" value=""EditMember"">" & "<input type=""hidden"" name=""form_MemberIndex"" value=""" & sqlDataReader.Item("Me_Index") & """>" & "</form>"
                        End If
                    End While
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If
        GetTeamMemberNames = str
    End Function

    Function GetLocationTeamNames(i, showEditLink)
        ' return a String list of Team names that are in a Location
        ' i = tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex
        ' Inactive teams are shown but include "*" at beginning of name
        ' showEditLink:
        '   if ShowEditLink = true, then add "Edit Team" form link to it
        '   CAN ONLY HAVE THIS if this generated form is not nested within a form
        Dim sSqlString, str
        str = ""
        If i.ToString = "" Or IsDBNull(i) Then
            ' skip
        Else
            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_Name, tab_Teams.Te_Active FROM tab_Teams" & " WHERE tab_Teams.Te_LocationIndex = " & i & " ORDER BY tab_Teams.Te_SortOrder;"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'sn' is NULL<br>", False, False)
                    GetLocationTeamNames = ""
                Else
                    'On Error GoTo 0
                    While sqlDataReader.Read = True
                        If str = "" Then
                            If Not IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                If sqlDataReader.Item("Te_Active") = "Yes" Then
                                    str = sqlDataReader.Item("Te_Name")
                                Else
                                    str = "*" & sqlDataReader.Item("Te_Name")
                                End If
                            End If
                        Else
                            If Not IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                If sqlDataReader.Item("Te_Active") = "Yes" Then
                                    str = str & "; " & sqlDataReader.Item("Te_Name")
                                Else
                                    str = str & "; " & "*" & sqlDataReader.Item("Te_Name")
                                End If
                            End If
                        End If
                        If showEditLink = True Then
                            str = str & " <form name=""fTe" & sqlDataReader.Item("Te_Index") & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=Edit"" method=""POST"" style=""margin:0;display:inline;"">" & "<a class=""submitAsLink"" onclick=""fTe" & sqlDataReader.Item("Te_Index") & ".submit()"">" & "<small>Edit</small></a>" & "<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">" & "<input type=""hidden"" name=""form_TeamIndex"" value=""" & sqlDataReader.Item("Te_Index") & """>" & "</form>"
                        End If
                    End While
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
        GetLocationTeamNames = str
    End Function

    Function GetSiteLocationNames(sn, showEditLink)
        ' return a String list of location names that are in a Site
        ' sn = tab_Sites.Si_SiteNum = tab_Locations.Lo_SiteNum
        ' Inactive sites are shown but include "*" at beginning of name
        ' showEditLink:
        '   if ShowEditLink = true, then add "Edit Location" form link to it
        '   CAN ONLY HAVE THIS if this generated form is not nested within a form
        Dim sSqlString, str
        str = ""
        If sn.ToString = "" Or IsDBNull(sn) Then
            ' skip
        Else
            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations" & " WHERE tab_Locations.Lo_SiteNum = '" & sn & "'"
            If Me.AdminType <> "All" Then
                sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
            End If
            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SortOrder;"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'sn' is NULL<br>", False, False)
                    GetSiteLocationNames = ""
                Else
                    'On Error GoTo 0
                    While sqlDataReader.Read = True
                        If str = "" Then
                            If Not IsDBNull(sqlDataReader.Item("Lo_Name")) Then
                                If sqlDataReader.Item("Lo_Active") = "Yes" Then
                                    str = sqlDataReader.Item("Lo_Name")
                                Else
                                    str = "*" & sqlDataReader.Item("Lo_Name")
                                End If
                            End If
                        Else
                            If Not IsDBNull(sqlDataReader.Item("Lo_Name")) Then
                                If sqlDataReader.Item("Lo_Active") = "Yes" Then
                                    str = str & "; " & sqlDataReader.Item("Lo_Name")
                                Else
                                    str = str & "; " & "*" & sqlDataReader.Item("Lo_Name")
                                End If
                            End If
                        End If
                        If showEditLink = True Then
                            str = str & " <form name=""fLo" & sqlDataReader.Item("Lo_Index") & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=Edit"" method=""POST"" style=""margin:0;display:inline;"">" & "<a class=""submitAsLink"" onclick=""fLo" & sqlDataReader.Item("Lo_Index") & ".submit()"">" & "<small>Edit</small></a>" & "<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">" & "<input type=""hidden"" name=""form_LocationIndex"" value=""" & sqlDataReader.Item("Lo_Index") & """>" & "</form>"
                        End If
                    End While
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
        GetSiteLocationNames = str
    End Function

    Function GetSiteNames(showEditLink)
        ' return a String list of Site names
        ' Inactive sites are shown but include "*" at beginning of name
        ' showEditLink:
        '   if ShowEditLink = true, then add "Edit Site" form link to it
        '   CAN ONLY HAVE THIS if this generated form is not nested within a form
        Dim sSqlString, str
        str = ""
        sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000'"
        If Me.AdminSite <> "000" Then
            sSqlString = sSqlString & " AND tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
        End If
        sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
        'On Error Resume Next


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Err.Number <> 0 Then
                Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>GetSiteNames()<br>", False, False)
                GetSiteNames = ""
            Else
                'On Error GoTo 0
                While sqlDataReader.Read = True
                    If str = "" Then
                        If Not IsDBNull(sqlDataReader.Item("Si_Name")) Then
                            If sqlDataReader.Item("Si_Active") = "Yes" Then
                                str = sqlDataReader.Item("Si_Name")
                            Else
                                str = "*" & sqlDataReader.Item("Si_Name")
                            End If
                        End If
                    Else
                        If Not IsDBNull(sqlDataReader.Item("Si_Name")) Then
                            If sqlDataReader.Item("Si_Active") = "Yes" Then
                                str = str & "; " & sqlDataReader.Item("Si_Name")
                            Else
                                str = str & "; " & "*" & sqlDataReader.Item("Si_Name")
                            End If
                        End If
                    End If
                    If showEditLink = True Then
                        str = str & " <form name=""fSi" & sqlDataReader.Item("Si_SiteNum") & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=Edit"" method=""POST"" style=""margin:0;display:inline;"">" & "<a class=""submitAsLink"" onclick=""fSi" & sqlDataReader.Item("Si_SiteNum") & ".submit()"">" & "<small>Edit</small></a>" & "<input type=""hidden"" name=""form_Choice"" value=""EditSite"">" & "<input type=""hidden"" name=""form_SiteNum"" value=""" & sqlDataReader.Item("Si_SiteNum") & """>" & "</form>"
                    End If
                End While
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        GetSiteNames = str
    End Function

    Function GetReasonFromScriptIndex(i)
        ' i = tab_Scripts.Sc_Index
        Dim sSqlString

        GetReasonFromScriptIndex = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetReasonFromScriptIndex = ""
        Else
            sSqlString = "SELECT tab_Reasons.Re_Name FROM tab_Reasons LEFT JOIN tab_Scripts ON tab_Reasons.Re_Index = tab_Scripts.Sc_ReasonIndex WHERE tab_Scripts.Sc_Index = " & i & ";"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetReasonFromScriptIndex = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetReasonFromScriptIndex = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Re_Name")) Then
                            GetReasonFromScriptIndex = ""
                        Else
                            GetReasonFromScriptIndex = sqlDataReader.Item("Re_Name")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetReason(i)
        ' i = tab_Reasons.Re_Index
        Dim sSqlString

        GetReason = ""

        If i = 0 Or IsDBNull(i) Then
            GetReason = ""
        Else
            sSqlString = "SELECT tab_Reasons.Re_Name FROM tab_Reasons WHERE tab_Reasons.Re_Index = " & i & ";"
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetReason = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetReason = ""
                    Else
                        If IsDBNull(sqlDataReader.Item("Re_Name")) Then
                            GetReason = ""
                        Else
                            GetReason = sqlDataReader.Item("Re_Name")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Function GetTypeFromLocationIndex(i)
        ' i = tab_Locations.Lo_Index = tab_Messages.LocationIndex = tab_Teams.Te_LocationIndex

        GetTypeFromLocationIndex = ""

        If i.ToString = "" Or IsDBNull(i) Then
            GetTypeFromLocationIndex = ""
        Else

            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = "SELECT tab_Locations.Lo_Type FROM tab_Locations WHERE tab_Locations.Lo_Index = " & i & ";"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    GetTypeFromLocationIndex = "Missing"
                Else
                    sqlDataReader.Read()

                    If IsDBNull(sqlDataReader.Item("Lo_Type")) Then
                        GetTypeFromLocationIndex = "Missing"
                    Else
                        GetTypeFromLocationIndex = sqlDataReader.Item("Lo_Type")
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If
    End Function

    Function GetTypeFromTeamIndex(i)
        ' i = tab_Teams.Te_Index
        Dim sSqlString

        GetTypeFromTeamIndex = "Missing"

        If IsDBNull(i) Then
            GetTypeFromTeamIndex = ""
        Else
            sSqlString = "SELECT tab_Locations.Lo_Type FROM tab_Locations LEFT JOIN tab_Teams ON tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex WHERE tab_Teams.Te_Index = " & i & ";"
            If _clsMessageVAR.BDebug = True Then
                Response.Write("sSqlString=" & sSqlString & "<br>")
            End If
            'On Error Resume Next


            Dim strConn As String
            Dim sqlDataReader As SqlDataReader = Nothing

            strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

            Dim MyConnection = New SqlConnection(strConn)
            Dim MyCommand As New SqlCommand()
            MyCommand.Connection = MyConnection
            MyCommand.CommandType = CommandType.Text

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Err.Number <> 0 Then
                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The likely reason is 'i' is NULL<br>", False, False)
                    GetTypeFromTeamIndex = ""
                Else
                    'On Error GoTo 0
                    If sqlDataReader.Read = False Then
                        GetTypeFromTeamIndex = "Missing"
                    Else
                        If IsDBNull(sqlDataReader.Item("Lo_Type")) Then
                            GetTypeFromTeamIndex = "Missing"
                        Else
                            GetTypeFromTeamIndex = sqlDataReader.Item("Lo_Type")
                        End If
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Function

    Sub ParseFullID(fullID)
        ' fullID: passed in as either form field or database field
        ' global values that are filled in when calling 
        Me.GLAST = ""
        Me.GFIRST = ""
        Me.GSSN = ""

        ' expected format:
        '   LAST,FIRST (xxxx)
        ' others used
        '   LAST, FIRST (xxxx)
        '   LAST, FIRST
        '   LAST,FIRST M (xxxx)
        '   LAST,FIRST M M (xxxx)
        '   LAST,FIRST MIDDLE (xxxx)
        '   LAST, FIRST xxxx
        '   LAST,FIRST xxxx
        '   LAST, FIRST(xxxx
        '   LAST,FIRST  xxx-xxx-xxxx
        Dim arrOne, arrTwo

        If fullID = "" Or IsDBNull(fullID) Then
            ' Nothing
        Else
            If _clsMessageVAR.BDebug = True Then
                Response.Write("FULLID.1=" & fullID & ".<br>")
            End If

            ' First the specialized character cleanups
            ' dump out ()#@
            '   do not remove "-" here because it could be valid in LastName segment
            fullID = Replace(fullID, "(", " ")
            fullID = Replace(fullID, ")", " ")
            fullID = Replace(fullID, "#", " ")
            fullID = Replace(fullID, "@", " ")

            ' dump out "," at end if that's what was entered (over copy/paste?)
            If Right(fullID, 1) = "," Then
                fullID = Left(fullID, Len(fullID) - 1)
            End If

            ' Dump everything left of ":"
            ' Sample: "Mgt Module Feb ent: LAST,FIRST M (xxxx) "
            If InStr(fullID, ":") Then
                fullID = Right(fullID, Len(fullID) - InStr(fullID, ":"))
                'Response.Write("FULLID.:=" & fullID & ".<br>")
            End If
            '	' sometimes has "Patient: " in the beginning
            '	if Left(fullID, 9) = "Patient: " then
            '		fullID = Right(fullID, Len(fullID)-9)
            '	end if

            ' sometimes has "Mgt Module " at the beginning
            If Left(fullID, 11) = "Mgt Module " Then
                fullID = Right(fullID, Len(fullID) - 11)
            End If

            ' sometimes has "Module " at the beginning
            If Left(fullID, 7) = "Module " Then
                fullID = Right(fullID, Len(fullID) - 7)
            End If

            ' sometimes has "/" in place of ","
            ' example:   "LAST/FIRST NNNN"
            If InStr(fullID, "/") And InStr(fullID, " ") Then
                If InStr(fullID, "/") < InStr(fullID, " ") Then
                    ' make sure the "/" is between LAST and FIRST
                    ' (because that's the only situation I've seen this used so only account for that)
                    fullID = Replace(fullID, "/", ",")
                End If
            End If

            ' Now the regular cleanup
            ' covert "," to ", "
            fullID = Replace(fullID, ",", ", ")

            ' dump out leading or trailing whitespace
            Do While Left(fullID, 1) = " "
                fullID = Right(fullID, Len(fullID) - 1)
            Loop
            Do While Right(fullID, 1) = " "
                fullID = Left(fullID, Len(fullID) - 1)
            Loop

            ' dump out double spaces
            Do While InStr(fullID, "  ")
                fullID = Replace(fullID, "  ", " ")
            Loop
            If _clsMessageVAR.BDebug = True Then
                Response.Write("FULLID.2=" & fullID & ".<br>")
            End If

            ' new formats limited down to:
            '   LAST, FIRST xxxx
            '   LAST, FIRST M xxxx
            '   LAST, FIRST M M xxxx
            '   LAST, FIRST MIDDLE xxxx

            If InStr(fullID, ", ") Then
                ' gLAST
                ' up to the comma (= full last name)
                arrOne = Split(fullID & ", zzzzzz", ", ")
                ' arrOne(0) = "LAST"
                ' arrOne(1) = "FIRST"
                ' arrOne(1) = "FIRST xxxx"
                ' arrOne(1) = "FIRST M xxxx"
                ' arrOne(1) = "FIRST M M xxxx"
                ' arrOne(1) = "FIRST MIDDLE xxxx"
                ' arrOne(1) = "FIRST xxx-xx-xxxx"
                ' arrOne(1) = "zzzzzz"
                Me.GLAST = arrOne(0)

                ' gFIRST
                If arrOne(1) <> "zzzzzz" Then
                    ' pull out "-" from SSN
                    ' "-" could be in last name, but not in first name
                    arrTwo = Split(Replace(arrOne(1), "-", "") & " zzzzzz", " ")
                    '1 arrTwo = {"xxxx", "zzzzzz"}
                    '2 arrTwo = {"FIRST", "zzzzzz"}
                    '3 arrTwo = {"FIRST", "xxxx", "zzzzzz"}
                    '4 arrTwo = {"FIRST", "M", "xxxx", "zzzzzz"}
                    '5 arrTwo = {"FIRST", "M", "M", "xxxx", "zzzzzz"}
                    '6 arrTwo = {"FIRST", "MIDDLE", "xxxx", "zzzzzz"}
                    '7 arrTwo = {"FIRST", "MIDDLE", "xxxxxxxxx", "zzzzzz"}
                    If IsNumeric(arrTwo(0)) Then
                        ' 1
                        Me.GSSN = arrTwo(0)
                    Else
                        ' 2-7
                        Me.GFIRST = arrTwo(0)
                        If arrTwo(1) = "zzzzzz" Then
                            ' 2
                            ' No SSN, done
                        Else
                            If IsNumeric(arrTwo(1)) Then
                                ' 3
                                Me.GSSN = arrTwo(1)
                            Else
                                ' 4-7
                                ' drop M or M M or MIDDLE, don't care
                                If arrTwo(2) <> "zzzzzz" Then
                                    If IsNumeric(arrTwo(2)) Then
                                        ' 4, 6, 7
                                        Me.GSSN = arrTwo(2)
                                    Else
                                        ' 5
                                        If arrTwo(3) <> "zzzzzz" Then
                                            If IsNumeric(arrTwo(3)) Then
                                                ' 5
                                                Me.GSSN = arrTwo(3)
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                Else
                    ' nothing after the last name?
                End If
            Else
                ' no comma so it's SSN or something else goofy?
            End If

            If Len(Me.GSSN) > 4 Then
                Me.GSSN = Right(Me.GSSN, 4)
            End If

            ' sometimes no space between FIRST and SSN
            If IsNumeric(Right(Me.GFIRST, 4)) And Me.GSSN = "" Then
                ' sample: Presley,Elvis0000"
                'Response.Write("gFIRST=" & gFIRST & ",gSSN=" & gSSN & ".<br>")
                Me.GSSN = Right(Me.GFIRST, 4)
                Me.GFIRST = Left(Me.GFIRST, Len(Me.GFIRST) - 4)
                'Response.Write("gFIRST=" & gFIRST & ",gSSN=" & gSSN & ".<br>")
            End If
            ' sometimes "/" was between FIRST and SSN
            If InStr(Me.GFIRST, "/") Then
                Me.GFIRST = Replace(Me.GFIRST, "/", "")
            End If

            ' catch entries with "Module Jan 25, 2010@ LAST,FIRST MIDDLE (xxxx)"
            If IsDate(Me.GLAST & " " & Me.GFIRST) Then
                'Response.Write("BreakdownDate=" & gLAST & ", " & gFIRST & " (" & gSSN & ")<br>")
                Me.GLAST = ""
                Me.GFIRST = ""
                Me.GSSN = ""
            End If
            If _clsMessageVAR.BDebug = True Then
                Response.Write("Breakdown=" & Me.GLAST & ", " & Me.GFIRST & " (" & Me.GSSN & ")<br>")
            End If
            'if IsNull(gLAST) then gLAST = "" end if
            'if IsNull(gFIRST) then gFIRST = "" end if
            'if IsNull(gSSN) then gSSN = "" end if
        End If
    End Sub

    '---Validate email
    Function isValidEmail(myEmail)
        Dim isValidE
        Dim regEx

        isValidE = True
        regEx = New RegExp

        regEx.IgnoreCase = False

        ' apostrophe in left side is allowed
        regEx.Pattern = "^([A-Za-z0-9_\-\.\'])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$"
        isValidE = regEx.Test(myEmail)

        isValidEmail = isValidE
    End Function

    Function isValidsSqlString(strOrig)
        ' checks the makeValidsSqlString string against the original string
        ' return true if valid string
        ' return false if different (contains Injection)
        Dim strInjection

        If strOrig Is Nothing Then
            isValidsSqlString = True
        Else
            ' copy the string so as not to change the original called in value
            strInjection = strOrig
            strInjection = Me.makeValidsSqlString(strInjection)
            If StrComp(strOrig, strInjection) = 0 Then
                isValidsSqlString = True
            Else
                isValidsSqlString = False
            End If
        End If
    End Function

    '---Function to help protect against sSqlString injection
    Function makeValidsSqlString(data)
        ' INPUT: string of free text to be stored in sSqlString
        ' OUTPUT: same string minus the injection code

        If _clsMessageVAR.BDebug = True Then
            Response.Write("dataIN=" & data & "<br>")
        End If

        Dim reg

        'data = True
        reg = New Regex("<[^>]*(>|$)")

        'reg.IgnoreCase = True
        'reg.Global = True

        'HTML - Non recognized codes
        ' single apostrophe is OK for all text fields, not removing
        'reg.Pattern = "'"
        'data = reg.Replace(data, " ")

        'HTML and CFML : skipping exempt fields and cleaning all others.
        data = reg.Replace(data, "")
        reg = Nothing

        'SYSTEM CALLS
        reg = New Regex(" *sp_ *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *dt_ *")
        data = reg.Replace(data, "")
        reg = Nothing

        'DELETES
        reg = New Regex(" *; *delete *from *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *delete *from *")
        data = reg.Replace(data, "")
        reg = Nothing

        'SELECTS AND PASSED SUB-SELECTS
        reg = New Regex(" *\( *select *from  *\) *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *; *select *\* *from *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *select *\* *from *")
        data = reg.Replace(data, "")
        reg = Nothing

        'INSERTIONS
        reg = New Regex(" *; *insert *into *\(  *\) *values *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *insert *into *\(  *\) *values *")
        data = reg.Replace(data, "")
        reg = Nothing

        'UPDATES
        reg = New Regex(" *; *update *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *update *set *= *")
        data = reg.Replace(data, "")
        reg = Nothing

        'CREATIONS
        reg = New Regex(" *create *proc *as *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *view *as *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *trigger *on *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *table *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *table *\(  *\) *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *database *on *\(  *\) *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *database *on *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *create *function *\(  *\) *as *")
        data = reg.Replace(data, "")
        reg = Nothing

        'ALTERATIONS
        reg = New Regex(" *alter *database *remove *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *alter *database *modify *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *alter *database *add *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *alter *proc *as *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *alter *view *as *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *alter *trigger *on *")
        data = reg.Replace(data, "")
        reg = Nothing

        'DROPS
        reg = New Regex(" *drop *trigger  *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *drop *view  *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *drop *table *")
        data = reg.Replace(data, "")
        reg = Nothing

        reg = New Regex(" *drop *database *")
        data = reg.Replace(data, "")
        reg = Nothing

        If _clsMessageVAR.BDebug = True Then
            Response.Write("dataOUT=" & data & "<br>")
        End If

        makeValidsSqlString = data
    End Function

    Function ColorizeFont(n)
        ' n = Team Name, some begin with color convention, comes from database field
        ' Output = return the team name as a matching font color string
        ' OPTIONAL FORCED CODING, append team name with space L Paren color R Paren
        ' Team Name (gold)
        ' Team Name (red)
        ' Team Name (green)
        ' Team Name (blue)
        ' Team Name (purple)
        ' Team Name (silver)
        ' Team Name (ruby)
        ' Team Name (emerald)
        Dim str
        If n <> "" And Not IsDBNull(n) Then
            str = UCase(n)
            ' format "Primary Care Blue 1" for colorizing
            str = Replace(str, "PRIMARY CARE ", "")
            str = Replace(str, "PACT ", "")
            ' don't use InStr(str, "color") because some team names are the name of the primary provider like "Greenhaugh" etc
            If Left(str, 4) = "GOLD" Or InStr(str, "(GOLD)") Then
                ' html gold is too light, use goldenrod for a bit more visibility
                n = Replace(n, " (GOLD)", "")
                n = Replace(n, " (gold)", "")
                n = Replace(n, " (Gold)", "")
                n = "<font color=""goldenrod"">" & n & "</font>"
            Else
                If Left(str, 3) = "RED" Or InStr(str, "(RED)") Then
                    ' html red too bright and used for errors, use firebrick instead
                    n = Replace(n, " (RED)", "")
                    n = Replace(n, " (red)", "")
                    n = Replace(n, " (Red)", "")
                    n = "<font color=""firebrick"">" & n & "</font>"
                Else
                    If Left(str, 5) = "GREEN" Or InStr(str, "(GREEN)") Then
                        ' html darkgreen instead of green is a bit more visible
                        n = Replace(n, " (GREEN)", "")
                        n = Replace(n, " (green)", "")
                        n = Replace(n, " (Green)", "")
                        n = "<font color=""darkgreen"">" & n & "</font>"
                    Else
                        If Left(str, 4) = "BLUE" Or InStr(str, "(BLUE)") Then
                            n = Replace(n, " (BLUE)", "")
                            n = Replace(n, " (blue)", "")
                            n = Replace(n, " (Blue)", "")
                            n = "<font color=""blue"">" & n & "</font>"
                        Else
                            If Left(str, 6) = "PURPLE" Or InStr(str, "(PURPLE)") Then
                                n = Replace(n, " (PURPLE)", "")
                                n = Replace(n, " (purple)", "")
                                n = Replace(n, " (Purple)", "")
                                n = "<font color=""purple"">" & n & "</font>"
                            Else
                                If Left(str, 6) = "SILVER" Or InStr(str, "(SILVER)") Then
                                    ' html gray, silver is too light
                                    n = Replace(n, " (SILVER)", "")
                                    n = Replace(n, " (silver)", "")
                                    n = Replace(n, " (Silver)", "")
                                    n = "<font color=""gray"">" & n & "</font>"
                                Else
                                    If Left(str, 4) = "RUBY" Or InStr(str, "(RUBY)") Then
                                        ' html crimson for ruby
                                        n = Replace(n, " (RUBY)", "")
                                        n = Replace(n, " (ruby)", "")
                                        n = Replace(n, " (Ruby)", "")
                                        n = "<font color=""crimson"">" & n & "</font>"
                                    Else
                                        If Left(str, 7) = "EMERALD" Or InStr(str, "(EMERALD)") Then
                                            ' html limegreen for emerald
                                            n = Replace(n, " (EMERALD)", "")
                                            n = Replace(n, " (emerald)", "")
                                            n = Replace(n, " (Emerald)", "")
                                            n = "<font color=""limegreen"">" & n & "</font>"
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
        ColorizeFont = n
    End Function
    Function ColorizeTeamBackgroundTD(n)
        ' n = Team Name, some begin with color convention, comes from database field
        ' Output = return the team name as a matching TD background color string
        ' OPTIONAL FORCED CODING, append team name with space L Paren color R Paren
        ' Team Name (gold)
        ' Team Name (red)
        ' Team Name (green)
        ' Team Name (blue)
        ' Team Name (purple)
        ' Team Name (silver)
        ' Team Name (ruby)
        ' Team Name (emerald)
        Dim str
        If n <> "" And Not IsDBNull(n) Then
            str = UCase(n)
            ' format "Primary Care Blue 1" for colorizing
            str = Replace(str, "PRIMARY CARE ", "")
            str = Replace(str, "PACT ", "")
            ' don't use InStr(str, "color") because some team names are the name of the primary provider like "Greenhaugh" etc
            If Left(str, 4) = "GOLD" Or InStr(str, "(GOLD)") Then
                ' html gold is too light, use goldenrod for a bit more visibility
                n = Replace(n, " (GOLD)", "")
                n = Replace(n, " (gold)", "")
                n = Replace(n, " (Gold)", "")
                n = "<td style=background-color:goldenrod;color:black>" & n
            Else
                If Left(str, 3) = "RED" Or InStr(str, "(RED)") Then
                    ' html red too bright and used for errors, use firebrick instead
                    n = Replace(n, " (RED)", "")
                    n = Replace(n, " (red)", "")
                    n = Replace(n, " (Red)", "")
                    n = "<td style=background-color:firebrick;color:white>" & n
                Else
                    If Left(str, 5) = "GREEN" Or InStr(str, "(GREEN)") Then
                        ' html darkgreen instead of green is a bit more visible
                        n = Replace(n, " (GREEN)", "")
                        n = Replace(n, " (green)", "")
                        n = Replace(n, " (Green)", "")
                        n = "<td style=background-color:darkgreen;color:white>" & n
                    Else
                        If Left(str, 4) = "BLUE" Or InStr(str, "(BLUE)") Then
                            n = Replace(n, " (BLUE)", "")
                            n = Replace(n, " (blue)", "")
                            n = Replace(n, " (Blue)", "")
                            n = "<td style=background-color:blue;color:white>" & n
                        Else
                            If Left(str, 6) = "PURPLE" Or InStr(str, "(PURPLE)") Then
                                n = Replace(n, " (PURPLE)", "")
                                n = Replace(n, " (purple)", "")
                                n = Replace(n, " (Purple)", "")
                                n = "<td style=background-color:purple;color:white>" & n
                            Else
                                If Left(str, 6) = "SILVER" Or InStr(str, "(SILVER)") Then
                                    ' html gray, silver is too light
                                    n = Replace(n, " (SILVER)", "")
                                    n = Replace(n, " (silver)", "")
                                    n = Replace(n, " (Silver)", "")
                                    n = "<td style=background-color:gray;color:white>" & n
                                Else
                                    If Left(str, 4) = "RUBY" Or InStr(str, "(RUBY)") Then
                                        ' html crimson for ruby
                                        n = Replace(n, " (RUBY)", "")
                                        n = Replace(n, " (ruby)", "")
                                        n = Replace(n, " (Ruby)", "")
                                        n = "<td style=background-color:crimson;color:white>" & n
                                    Else
                                        If Left(str, 7) = "EMERALD" Or InStr(str, "(EMERALD)") Then
                                            ' html limegreen for emerald
                                            n = Replace(n, " (EMERALD)", "")
                                            n = Replace(n, " (emerald)", "")
                                            n = Replace(n, " (Emerald)", "")
                                            n = "<td style=background-color:limegreen;color:black>" & n
                                        Else
                                            ' Default to inherit
                                            n = "<td style=background-color:inherit;color:inherit>" & n
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Else
            ' Default to inherit in case we have a bogus Team Name value passed
            n = "<td style=background-color:inherit;color:inherit>" & n
        End If
        ColorizeTeamBackgroundTD = n
    End Function
    Function ColorizeTeamName(n)
        ' n = Team Name, some begin with color convention, comes from database field
        ' Output = return the team name as a matching TD background color string
        ' OPTIONAL FORCED CODING, append team name with space L Paren color R Paren
        ' Team Name (gold)
        ' Team Name (red)
        ' Team Name (green)
        ' Team Name (blue)
        ' Team Name (purple)
        ' Team Name (silver)
        ' Team Name (ruby)
        ' Team Name (emerald)
        Dim str
        If n <> "" And Not IsDBNull(n) Then
            str = UCase(n)
            ' format "Primary Care Blue 1" for colorizing
            str = Replace(str, "PRIMARY CARE ", "")
            str = Replace(str, "PACT ", "")
            ' don't use InStr(str, "color") because some team names are the name of the primary provider like "Greenhaugh" etc
            If Left(str, 4) = "GOLD" Or InStr(str, "(GOLD)") Then
                ' html gold is too light, use goldenrod for a bit more visibility
                n = Replace(n, " (GOLD)", "")
                n = Replace(n, " (gold)", "")
                n = Replace(n, " (Gold)", "")
                n = "<font style=background-color:goldenrod;color:black>" & n & "</font>"
            Else
                If Left(str, 3) = "RED" Or InStr(str, "(RED)") Then
                    ' html red too bright and used for errors, use firebrick instead
                    n = Replace(n, " (RED)", "")
                    n = Replace(n, " (red)", "")
                    n = Replace(n, " (Red)", "")
                    n = "<font style=background-color:firebrick;color:white>" & n & "</font>"
                Else
                    If Left(str, 5) = "GREEN" Or InStr(str, "(GREEN)") Then
                        ' html darkgreen instead of green is a bit more visible
                        n = Replace(n, " (GREEN)", "")
                        n = Replace(n, " (green)", "")
                        n = Replace(n, " (Green)", "")
                        n = "<font style=background-color:darkgreen;color:white>" & n & "</font>"
                    Else
                        If Left(str, 4) = "BLUE" Or InStr(str, "(BLUE)") Then
                            n = Replace(n, " (BLUE)", "")
                            n = Replace(n, " (blue)", "")
                            n = Replace(n, " (Blue)", "")
                            n = "<font style=background-color:blue;color:white>" & n & "</font>"
                        Else
                            If Left(str, 6) = "PURPLE" Or InStr(str, "(PURPLE)") Then
                                n = Replace(n, " (PURPLE)", "")
                                n = Replace(n, " (purple)", "")
                                n = Replace(n, " (Purple)", "")
                                n = "<font style=background-color:purple;color:white>" & n & "</font>"
                            Else
                                If Left(str, 6) = "SILVER" Or InStr(str, "(SILVER)") Then
                                    ' html gray, silver is too light
                                    n = Replace(n, " (SILVER)", "")
                                    n = Replace(n, " (silver)", "")
                                    n = Replace(n, " (Silver)", "")
                                    n = "<font style=background-color:gray;color:white>" & n & "</font>"
                                Else
                                    If Left(str, 4) = "RUBY" Or InStr(str, "(RUBY)") Then
                                        ' html crimson for ruby
                                        n = Replace(n, " (RUBY)", "")
                                        n = Replace(n, " (ruby)", "")
                                        n = Replace(n, " (Ruby)", "")
                                        n = "<font style=background-color:crimson;color:white>" & n & "</font>"
                                    Else
                                        If Left(str, 7) = "EMERALD" Or InStr(str, "(EMERALD)") Then
                                            ' html limegreen for emerald
                                            n = Replace(n, " (EMERALD)", "")
                                            n = Replace(n, " (emerald)", "")
                                            n = Replace(n, " (Emerald)", "")
                                            n = "<font style=background-color:limegreen;color:black>" & n & "</font>"
                                        Else
                                            ' Default to inherit
                                            n = "<font style=background-color:inherit;color:inherit>" & n & "</font>"
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Else
            ' Default to inherit in case we have a bogus Team Name value passed
            n = "<font style=background-color:inherit;color:inherit>" & n & "</font>"
        End If
        ColorizeTeamName = n
    End Function
    Function formatTime(t, bSec)
        ' t = "12:45:15 PM" 
        ' t = "13:22."
        ' t = "15:31:49.0000000"
        ' bSec = true/false, determines if seconds are included or not
        ' output as "12:45p"
        ' truncates seconds
        Dim str, ampm, arr
        Dim h, m, sec
        str = t.ToString()
        If str <> "" Then
            str = UCase(str)
            str = Replace(str, " ", "")
            If InStr(str, ".") Then
                str = Left(str, InStr(str, ".") - 1)
            End If
            ampm = Right(str, 2)
            str = Replace(str, "PM", "")
            str = Replace(str, "AM", "")
            arr = Split(str & ":99:99:99", ":")
            h = arr(0)
            If InStr(h, "/") Then
                ' Date/Time as time may cause this issue
                ' "10/15/201208" from "10/15/2012 08:15:65 PM"
                h = Right(h, 2)
            End If
            h = CInt(h)
            m = arr(1)
            sec = arr(2)
            If bSec = True Then
                Select Case ampm
                    Case "PM"
                        str = h & ":" & m & ":" & sec & "PM"
                    Case "AM"
                        str = h & ":" & m & ":" & sec & "AM"
                    Case Else
                        If h < 12 Then
                            str = h & ":" & m & ":" & sec & "AM"
                        Else
                            If h = 12 Then
                                str = "12:" & m & ":" & sec & "PM"
                            Else
                                str = h - 12 & ":" & m & ":" & sec & "PM"
                            End If
                        End If
                End Select
            Else
                Select Case ampm
                    Case "PM"
                        str = h & ":" & m & "PM"
                    Case "AM"
                        str = h & ":" & m & "AM"
                    Case Else
                        If h < 12 Then
                            str = h & ":" & m & "AM"
                        Else
                            If h = 12 Then
                                str = "12:" & m & "PM"
                            Else
                                str = h - 12 & ":" & m & "PM"
                            End If
                        End If
                End Select
            End If
        End If
        formatTime = str
    End Function

    Function DayLetter(d)
        Select Case d
            Case 1
                DayLetter = "Su"
            Case 2
                DayLetter = "M"
            Case 3
                DayLetter = "T"
            Case 4
                DayLetter = "W"
            Case 5
                DayLetter = "Th"
            Case 6
                DayLetter = "F"
            Case 7
                DayLetter = "Sa"
            Case Else
                DayLetter = ""
        End Select
    End Function

    ' this version is horribly slow as it's called from a nested loop = n*m times and thus the database lookup is n*m times
    'function IsHoliday(d)
    '	' d = valid Date in question
    '	' if not a holiday, returns ""
    '	' if a holiday, returns the Holiday Name
    '	dim sSqlString, hrs, HO
    '	' #date# for access, 'date' for sSqlString
    '	if bUsesSqlString = true then
    '		sSqlString = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays WHERE tab_Holidays.Ho_Date = '" & d & "';"
    '	else
    '		sSqlString = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays WHERE tab_Holidays.Ho_Date = #" & d & "#;"
    '	end if
    '	set hrs = db.Execute(sSqlString)
    '	if hrs.EOF then
    '		' not a holiday
    '		HO = ""
    '	else
    '		' holiday
    '		if IsNull(hrs("Ho_Name")) then
    '			HO = ""
    '		else
    '			HO = hrs("Ho_Name")
    '		end if
    '	end if
    '	set hrs = nothing
    '	IsHoliday = HO
    'end function
    Function IsHoliday(dHol)


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        ' dHol = valid Date in question
        ' if not a holiday, returns ""
        ' if a holiday, returns the Holiday Name
        '
        ' Holidays stored in Application variables:
        ' [Application Variable Name], [Application Variable Value]
        ' ---------------------------, ----------------------------
        ' (appCrDate, 10/23/2012)
        ' MS ACCESS stores Date like this:
        '   1/1/2013  creates AppVar: (Ho.1/1/2013="New Year's Day")
        '   1/21/2013 creates AppVar: (Ho.1/21/2013="Martin Luther Kin, Jr Day")
        '   etc, etc
        ' sSqlString stores it like this:
        '   2013-1-1  creates AppVar: (Ho.2013-1-1="New Year's Day")
        '   2013-1-21 creates AppVar: (Ho.2013-1-21="Martin Luther Kin, Jr Day")
        '   etc, etc

        If _clsMessageVAR.BDebug = True Then
            Response.Write("Hol.Before.dHol=" & dHol & "<br>")
        End If
        If _clsMessageVAR.BUsesSqlString = True Then
            ' flip "dHol" value from "M/D/YYYY" to "YYYY-M-D"
            Dim dYear, dMonth, dDay
            dYear = DatePart("yyyy", dHol)
            dMonth = DatePart("m", dHol)
            dDay = DatePart("d", dHol)
            dHol = dMonth & "/" & dDay & "/" & dYear
        End If
        If _clsMessageVAR.BDebug = True Then
            Response.Write("Hol.After.dHol=" & dHol & "<br>")
        End If

        Dim bAppReload, appCrDate
        bAppReload = False
        appCrDate = Application("Ho.CrDate")
        If _clsMessageVAR.BDebug = True Then
            Response.Write("appCrDate=" & appCrDate & ".<br>")
        End If

        ' check for valid Application age, must be stored today
        If Not IsDate(appCrDate) Then
            bAppReload = True
        Else
            appCrDate = CDate(appCrDate)
            If DateDiff("d", appCrDate, theDate) <> 0 Then
                bAppReload = True
            End If
        End If

        If _clsMessageVAR.BDebug = True Then
            Response.Write("bAppReload=" & bAppReload & "<br>")
        End If

        If bAppReload = True Then
            ' create Array from database and store in Application
            MyCommand.CommandText = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays ORDER BY tab_Holidays.Ho_Date;"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If sqlDataReader.HasRows = True Then
                    ' store new Application values
                    Application.Lock()
                    Application("Ho.CrDate") = theDate

                    While sqlDataReader.Read = True
                        Application("Ho." & sqlDataReader.Item("Ho_Date")) = sqlDataReader.Item("Ho_Name")
                    End While

                    Application.UnLock()
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If

        ' return Holiday name for input variable "dHol" date
        If _clsMessageVAR.BDebug = True Then
            Response.Write("Application(Ho." & dHol & ")=" & Application("Ho." & dHol) & "<br>")
        End If
        IsHoliday = Application("Ho." & dHol)
    End Function

    Function ComputeDelay(SD, ST, ED, ET, Style)
        ' Style = {"BH"|"Weekdays"|"All"} to determine which value is returned
        ' Exclude weekends
        ' Exclude Holidays
        ' "BH"
        '	compute Delay in decimal hours
        '	8a - 5p only
        '	midnight to 8am = 8 hours, not counted
        '	8am to 5pm = 9 hours, counted
        '	5pm to midnight = 7 hours, not counted
        '	hours = seconds / 3600
        ' "Weekdays"
        '	compute Delay in Integer Days
        '	weekdays only, excluding holidays (tour of 8a-5p not used)
        '	same day (any time) = 0 Days
        '	next day (any time) = 1 Day
        ' "All"
        '	compute Delay in decimal hours
        '	24 hours in a day, tour of 8a-5p not used
        '	weekends, holidays not referenced
        Dim Accumulator As DateTime
        Dim dst, det
        Dim tBEGIN, tEND, h, bCountDay, hoursTour, countWeekdays, hoursAll
        hoursTour = 0
        countWeekdays = 0
        hoursAll = 0

        ' check for invalid input data
        If IsDBNull(SD) Or IsDBNull(ST) Or IsDBNull(ED) Or IsDBNull(ET) Then
            ' cannot Compute Delay.
            ComputeDelay = ""
        Else

            If Style = "All" Then
                SD = CDate(SD & " " & ST)
                ED = CDate(ED & " " & ET)
                hoursAll = DateDiff("s", SD, ED) / 3600
                'Response.Write("hoursAll=" & roundit(hoursAll,2) & " hours or " & roundit(hoursAll,2)/24 & " days<br>")	
            Else
                ' "BH" and "Weekdays"
                tBEGIN = CDate("08:00:00 AM")
                tEND = CDate("05:00:00 PM")

                ' formatTime is used to convert 14:32:06.0000000 to "12:32:06p"
                ' true passed in means to include seconds
                'Response.Write("before:SD,ST=" & SD & "," & ST & "<br>")
                'Response.Write("before:formatTime(ST)=" & formatTime(ST, true) & "<br>")
                SD = CDate(SD)
                ST = CDate(Me.formatTime(ST, True))
                'Response.Write("after:SD,ST=" & SD & "," & ST & "<br>")

                'Response.Write("before:ED,ET=" & ED & "," & ET & "<br>")
                'Response.Write("before:formatTime(ET)=" & formatTime(ET, true) & "<br>")
                ED = CDate(ED)
                ET = CDate(Me.formatTime(ET, True))
                'Response.Write("after:ED,ET=" & ED & "," & ET & "<br>")

                Accumulator = SD

                While (Accumulator <= ED)
                    ' Warning:  even though SD/ED is in format like "11/30/2012", d will become format like "2012-11-30"
                    bCountDay = True

                    'Response.Write("<u>d=" & d & "</u><br>")		
                    If Weekday(Accumulator) = 1 Or Weekday(Accumulator) = 7 Then
                        ' weekend, don't count
                        bCountDay = False
                        'Response.Write("WeekEnd (" & d & ")<br>")
                    Else
                        ' from the 5 weekdays remaining, cut out the holidays
                        If Me.IsHoliday(Accumulator) <> "" Then
                            bCountDay = False
                            'Response.Write("Holiday=" & IsHoliday(d) & "<br>")
                        End If
                    End If

                    ' now add the hours in this date to the running total
                    If bCountDay = True Then
                        If DateDiff("d", SD, ED) = 0 Then
                            ' strip off same day.  Loop only runs this 1 time
                            If DateDiff("s", ST, tBEGIN) > 0 Then
                                ' ST before 8am will return positive number
                                dst = tBEGIN
                                'Response.Write("dst = tBegin = " & dst & "<br>")
                            Else
                                If DateDiff("s", ST, tEND) < 0 Then
                                    ' ST after 5pm will return negative number
                                    dst = tEND
                                    'Response.Write("dst = tEND = " & dst & "<br>")
                                Else
                                    dst = ST
                                    'Response.Write("dst = ST = " & dst & "<br>")
                                End If
                            End If
                            If DateDiff("s", ET, tEND) < 0 Then
                                ' ET after 5pm will return negative number
                                det = tEND
                                'Response.Write("det = tEND = " & det & "<br>")
                            Else
                                If DateDiff("s", ET, tBEGIN) > 0 Then
                                    ' ET before 8am will return positive number
                                    det = tBEGIN
                                    'Response.Write("det = tBegin = " & det & "<br>")
                                Else
                                    det = ET
                                    'Response.Write("dst = ET = " & det & "<br>")
                                End If
                            End If
                            hoursTour = DateDiff("s", dst, det) / 3600
                            'Response.Write("hoursTour = " & hoursTour & "<br>")
                            'countWeekdays = DateDiff("s", cDate(SD & " " & ST), cDate(ED & " " & ET)) / 3600
                            countWeekdays = 0
                        Else
                            'Response.Write("...d=" & d & ", SD=" & SD & "<br>")
                            If DateDiff("d", Accumulator, SD) = 0 Then
                                ' Tour: reduced hours on first day, only add if the ST before 5pm
                                'Response.Write("Tour: reduced hours on first day, only add if the ST before 5pm<br>")
                                If DateDiff("s", ST, tEND) > 0 Then
                                    If DateDiff("s", ST, tBEGIN) > 0 Then
                                        dst = tBEGIN
                                        'Response.Write("dst = tBEGIN = " & dst & "<br>")
                                    Else
                                        dst = ST
                                        'Response.Write("dst = ST = " & dst & "<br>")
                                    End If
                                    hoursTour = DateDiff("s", dst, tEND) / 3600
                                    'Response.Write("hoursTour = " & hoursTour & "<br>")
                                End If
                                ' Old weekdays way: include only hours after start time
                                'countWeekdays = DateDiff("s", cDate(SD & " " & ST), cDate(DateAdd("d", SD, 1) & " 12:00:00 AM")) / 3600
                                countWeekdays = 0
                            Else
                                If DateDiff("d", Accumulator, ED) = 0 Then
                                    ' reduced hours on last day, only add if the ET after 8am
                                    'Response.Write("Tour: reduced hours on last day, only add if the ET after 8am<br>")
                                    If DateDiff("s", tBEGIN, ET) > 0 Then
                                        If DateDiff("s", tEND, ET) > 0 Then
                                            ' after 5pm, reset end time to 5pm
                                            det = tEND
                                        Else
                                            det = ET
                                        End If
                                        hoursTour = hoursTour + DateDiff("s", tBEGIN, det) / 3600
                                    End If
                                    ' old weekdays way: include only hours before end time
                                    'countWeekdays = countWeekdays + DateDiff("s", cDate(ED & " 12:00:00 AM"), cDate(ED & " " & ET)) / 3600
                                    countWeekdays = countWeekdays + 1
                                Else
                                    ' day in the middle
                                    'Response.Write("Tour: Day in the middle, count all the hours<br>")
                                    hoursTour = hoursTour + DateDiff("h", tBEGIN, tEND)
                                    countWeekdays = countWeekdays + 1
                                End If ' d = ED
                            End If ' d = SD
                        End If ' SD = ED
                    End If ' bCountDay = true
                    'Response.Write("hoursTour=" & roundit(hoursTour,2) & "<br>")	
                    'Response.Write("countWeekdays=" & roundit(countWeekdays,2) & " days<br><br>")

                    Accumulator = Accumulator.AddDays(1)
                End While

            End If ' Style = "All"
            Select Case Style
                Case "BH"
                    ComputeDelay = hoursTour
                Case "Weekdays"
                    ComputeDelay = countWeekdays
                Case Else
                    ' "All"
                    ComputeDelay = hoursAll
            End Select
        End If ' invalid input data
    End Function

    Function roundit(number, decPoints)
        ' VBScript's built-in round function leaves a lot to be desired. 
        ' seems to work a lot better in all cases: 
        If number = 0 Or IsDBNull(number) Or Double.IsNaN(Convert.ToDouble(number)) Then
            roundit = 0
        Else
            decPoints = 10 ^ decPoints
            roundit = Math.Round(number * decPoints + 0.1) / decPoints
        End If
    End Function

    Function roundClock(number)
        ' input "nn.ddddd"  (6.93000)
        ' convert the "nn" to "hh"  (6)
        ' convert the ".ddddd" to "mm"  (
        ' return as string "h:mm"

        If number.ToString = "" Or IsDBNull(number) Then
            roundClock = ""
        Else
            Dim h As Integer
            Dim m As Double
            Dim str
            h = Int(number)
            m = number - h
            m = m * 60
            m = Me.roundit(m, 0)

            str = h.ToString() & ":"
            If m < 0.01 Then
                str = str & "00"
            Else
                If m > 0 And m < 10 Then
                    ' insert leading zero
                    str = str & "0" & Right(m.ToString(), 1)
                Else
                    str = str & m.ToString()
                End If
            End If

            roundClock = str
        End If
    End Function

    Function SecSinceOverload()
        ' checks application variable "TIMEOUT"
        ' intitialized -3
        ' not a date -2
        ' if Nothing return -1
        ' else return seconds Diff from AppTimeout and Now()

        Dim TimeOutDate As DateTime, rVal
        rVal = -3
        TimeOutDate = Application("TIMEOUT")
        If IsDBNull(TimeOutDate) Then
            rVal = -1
        Else
            If IsDate(TimeOutDate) Then
                rVal = DateDiff("s", TimeOutDate, Now())
            Else
                rVal = -2
            End If
        End If

        SecSinceOverload = rVal
    End Function

    Function ShowAverage(ti, reason)
        ' ti = TeamIndex
        ' r = Reason string value that matches the Reasons table
        ' compute the average delay time 
        '	- for the last 100 completed Messages (or as many as there are up to the last 100) 
        '	- of this Type
        '	- for this team
        ' return a string "full response" to be displayed as is

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim sec
        sec = Me.SecSinceOverload()
        ' seconds.  if timeouts in last 10 minutes then don't show
        If sec >= 0 And sec < 600 Then
            ShowAverage = ""
        Else
            Dim sSqlString, r
            Dim count, cumTime, avgTime, s, days, hours, minutes

            MyCommand.CommandText = "SELECT TOP 100 tab_Messages.Msg_Index, tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm" & " FROM tab_Messages LEFT JOIN tab_Audit" & " ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_TeamIndex = " & ti & " AND tab_Messages.Msg_Reason = '" & Replace(reason, "'", "''") & "'"
            ' tab_Audit.Au_Action="Completed" will account for tab_Messages.Msg_Completed = 'Yes'"
            MyCommand.CommandText = MyCommand.CommandText & " AND tab_Audit.Au_Action = 'Completed' ORDER BY tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                count = 0
                cumTime = 0
                While sqlDataReader.Read = True And count < 100
                    ' cumTime = cumulative time in decimal business hours
                    cumTime = cumTime + Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "BH")
                    count = count + 1
                End While

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

            If count = 0 Then
                s = "There are no completed Messages, thus no average delay is predicted."
            Else
                s = "The average (business hour) completion rate for the last " & count & " <b>" & reason & "</b> messages for <b>" & Me.GetTeamName(ti) & "</b> is "

                ' avgTime is in decimal hours
                avgTime = cumTime / count
                If avgTime < 2 Then
                    ' display in minutes: 0 to 120
                    ' Round instead of Int because not showing the remainders.
                    minutes = avgTime * 60
                    minutes = Me.roundit(minutes, 0)
                Else
                    If avgTime > 48 Then
                        ' display in days: 2 to a really bad number
                        ' Int instead of Round because can't Round up when showing the remainders.
                        days = avgTime / 24
                        hours = avgTime Mod 24
                        minutes = (hours - Int(hours)) * 60
                        days = Int(days)
                        hours = Int(hours)
                        minutes = Int(minutes)
                        If days = 1 Then
                            s = s & days & " day "
                        Else
                            s = s & days & " days "
                        End If
                    Else
                        ' display in hours: 2 to 48
                        ' Int instead of Round because can't Round up when showing the remainders.
                        hours = Int(avgTime)
                        minutes = (avgTime - hours) * 60
                        minutes = Int(minutes)
                    End If

                    If hours = 1 Then
                        s = s & hours & " hour and "
                    Else
                        s = s & hours & " hours and "
                    End If

                End If ' avgTime < 2

                ' minutes shown for all 3 time situations
                If minutes = 1 Then
                    s = s & minutes & " minute."
                Else
                    s = s & minutes & " minutes."
                End If

            End If ' count = 0

            ShowAverage = s
        End If ' 0 <= sec < 600
    End Function

    Function ShowReportAverage(ti, reason)
        ' ti = TeamIndex
        ' r = Reason string value that matches the Reasons table
        ' compute the average delay time 
        '	- for the last 100 completed Messages (or as many as there are up to the last 100) 
        '	- of this Type
        '	- for this team
        ' return a string "full response" to be displayed as is

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim sec
        sec = Me.SecSinceOverload()
        ' seconds.  if timeouts in last 10 minutes then don't show
        If sec >= 0 And sec < 600 Then
            ShowReportAverage = ""
        Else
            Dim count, cumTime, avgTime, s, days, hours, minutes

            MyCommand.CommandText = "SELECT TOP 100 tab_Messages.Msg_Index, tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm" & " FROM tab_Messages LEFT JOIN tab_Audit" & " ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_TeamIndex = " & ti & " AND tab_Messages.Msg_Reason = '" & Replace(reason, "'", "''") & "'"
            ' tab_Audit.Au_Action="Completed" will account for tab_Messages.Msg_Completed = 'Yes'"
            MyCommand.CommandText = MyCommand.CommandText & " AND tab_Audit.Au_Action = 'Completed' ORDER BY tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                count = 0
                cumTime = 0
                While sqlDataReader.Read = True And count < 100
                    ' cumTime = cumulative time in decimal business hours
                    cumTime = cumTime + Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "BH")
                    count = count + 1
                End While

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

            If count = 0 Then
                s = "No Messages found for Reason: " & reason
            Else
                s = "The average (business hour) completion rate for the last " & count & " <b>" & reason & "</b> messages for <b>" & Me.GetTeamName(ti) & "</b> is "

                ' avgTime is in decimal hours
                avgTime = cumTime / count
                If avgTime < 2 Then
                    ' display in minutes: 0 to 120
                    ' Round instead of Int because not showing the remainders.
                    minutes = avgTime * 60
                    minutes = Me.roundit(minutes, 0)
                Else
                    If avgTime > 48 Then
                        ' display in days: 2 to a really bad number
                        ' Int instead of Round because can't Round up when showing the remainders.
                        days = avgTime / 24
                        hours = avgTime Mod 24
                        minutes = (hours - Int(hours)) * 60
                        days = Int(days)
                        hours = Int(hours)
                        minutes = Int(minutes)
                        If days = 1 Then
                            s = s & days & " day "
                        Else
                            s = s & days & " days "
                        End If
                    Else
                        ' display in hours: 2 to 48
                        ' Int instead of Round because can't Round up when showing the remainders.
                        hours = Int(avgTime)
                        minutes = (avgTime - hours) * 60
                        minutes = Int(minutes)
                    End If

                    If hours = 1 Then
                        s = s & hours & " hour and "
                    Else
                        s = s & hours & " hours and "
                    End If

                End If ' avgTime < 2

                ' minutes shown for all 3 time situations
                If minutes = 1 Then
                    s = s & minutes & " minute."
                Else
                    s = s & minutes & " minutes."
                End If

            End If ' count = 0

            ShowReportAverage = s
        End If ' 0 <= sec < 600
    End Function

    Function ShowScript(strReason, LocIndex)
        ' strReason = Reason text string
        ' LocIndex = LocationIndex
        ' Scr_LocationIndex = 0 = DEFAULT = represents the default scrips for each Reason
        ' Scr_LocationIndex = {1, 2, 3, 4, ... N} = custom for each Location.  Default shown if this doesn’t exist
        ' returns the Memo field "Sc_Details"

        Dim result, rsDetails

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text
        ' sort by LocationIndex DESC to put the custom location before the default
        MyCommand.CommandText = "SELECT tab_Scripts.Sc_Details FROM tab_Scripts LEFT JOIN tab_Reasons" & " ON tab_Scripts.Sc_ReasonIndex = tab_Reasons.Re_Index" & " WHERE tab_Reasons.Re_Name = '" & Replace(strReason, "'", "''") & "'" & " AND (tab_Scripts.Sc_LocationIndex = 0 OR tab_Scripts.Sc_LocationIndex = " & LocIndex & ")" & " ORDER BY tab_Scripts.Sc_LocationIndex DESC;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                result = ""
            Else
                sqlDataReader.Read()

                rsDetails = sqlDataReader.Item("Sc_Details")
                If IsDBNull(rsDetails) Then
                    result = ""
                Else
                    result = rsDetails
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        ShowScript = result
    End Function

    Function ShowTitle()
        ' Member, Admin, Site
        Select Case Me.AdminAccess
            Case "Admin"
                If Me.AdminSite = "000" Then
                    ShowTitle = "System Admin"
                Else
                    ShowTitle = "Site Admin"
                End If
            Case "Site"
                If Me.AdminSite = "000" Then
                    ShowTitle = "System Manager"
                Else
                    ShowTitle = "Site Manager"
                End If
            Case "Member"
                ShowTitle = "Member"
            Case Else
                ShowTitle = "logged in"
        End Select
        Select Case Me.AdminType
            Case "All"
                ' nothing
            Case "None"
                ' nothing
            Case Else
                ' insert before tytle
                ShowTitle = Me.AdminType & " " & ShowTitle
        End Select
    End Function

    Function CreateTitleOption(ADT, title, desc)
        ' compare to see if can predict based on AD's Title
        ' doesn't matter if it misses some, those are still chosen by the user doing the edits

        Dim results, CAPSADT
        results = ""
        CAPSADT = UCase(ADT)
        ' strip out dots
        CAPSADT = Replace(CAPSADT, ".", "")

        Select Case title
            Case "Audiologist"
                ' see "ST" for Speech Therapist for similar rules
                If InStr(CAPSADT, "AUDIOLOG") > 0 Then
                    results = "<option value=""Audiologist"" selected>Audiologist</option>"
                Else
                    results = "<option value=""Audiologist"">Audiologist</option>"
                End If
            Case "Clerk"
                ' InStr(CAPSADT,"CLERK") or InStr(CAPSADT,"SECRETARY") are a mix of {Clerk, PSA, MSA} on the PACT side
                ' Ass covers Assitant or Asst
                If InStr(CAPSADT, "CLAIM CLERK") > 0 Or InStr(CAPSADT, "CLAIMS CLERK") > 0 Or InStr(CAPSADT, "CLAIMS ASS") > 0 Or InStr(CAPSADT, "FILE CLERK") > 0 Then
                    results = "<option value=""Clerk"" selected>Clerk</option>"
                Else
                    If InStr(CAPSADT, "FEE ") > 0 And (InStr(CAPSADT, "CLERK") > 0 Or InStr(CAPSADT, "SECRETARY") > 0) Then
                        results = "<option value=""Clerk"" selected>Clerk</option>"
                    Else
                        results = "<option value=""Clerk"">Clerk</option>"
                    End If
                End If
            Case "Chief"
                If InStr(CAPSADT, "CHIEF") > 0 Or InStr(CAPSADT, "PROGRAM MANAGER") > 0 Then
                    results = "<option value=""Chief"" selected>Chief</option>"
                Else
                    results = "<option value=""Chief"">Chief</option>"
                End If
            Case "DDS"
                If CAPSADT = "DDS" Or InStr(CAPSADT, "DENTIST") > 0 Then
                    results = "<option value=""DDS"" selected>DDS</option>"
                Else
                    results = "<option value=""DDS"">DDS</option>"
                End If
            Case "Dietician"
                If InStr(CAPSADT, "DIETICIAN") > 0 Then
                    results = "<option value=""Dietician"" selected>Dietician</option>"
                Else
                    results = "<option value=""Dietician"">Dietician</option>"
                End If
            Case "DO"
                ' "DO" Doctor of Osteopathy/Osteopathic Medicine
                If CAPSADT = "DO" Or (InStr(CAPSADT, "DOCTOR") > 0 And InStr(CAPSADT, "OSTEOPATH") > 0) Then
                    results = "<option value=""DO"" selected>DO</option>"
                Else
                    results = "<option value=""DO"">DO</option>"
                End If
            Case "DPM"
                If CAPSADT = "DPM" Or InStr(CAPSADT, "PODIATRIST") > 0 Then
                    results = "<option value=""DPM"" selected>DPM</option>"
                Else
                    results = "<option value=""DPM"">DPM</option>"
                End If
            Case "LPN"
                If CAPSADT = "LPN" Or InStr(CAPSADT, "LICENSED PRACTICAL NURSE") > 0 Then
                    results = "<option value=""LPN"" selected>LPN</option>"
                Else
                    results = "<option value=""LPN"">LPN</option>"
                End If
            Case "MD"
                If CAPSADT = "MD" Or CAPSADT = "PHYSICIAN" Or (InStr(CAPSADT, "PHYSICIAN") > 0 And (InStr(CAPSADT, "STAFF") > 0 Or InStr(CAPSADT, "ATTENDING") > 0 Or InStr(CAPSADT, "RESIDENT") > 0)) Then
                    ' but don't match "Physician Assistant"
                    results = "<option value=""MD"" selected>MD</option>"
                Else
                    results = "<option value=""MD"">MD</option>"
                End If
            Case "MSA"
                If CAPSADT = "MSA" Or InStr(CAPSADT, "MEDICAL SUPPORT ASSISTANT") > 0 Then
                    results = "<option value=""MSA"" selected>MSA</option>"
                Else
                    results = "<option value=""MSA"">MSA</option>"
                End If
            Case "NP"
                If CAPSADT = "NP" Or InStr(CAPSADT, "NURSE PRACTITIONER") > 0 Then
                    results = "<option value=""NP"" selected>NP</option>"
                Else
                    results = "<option value=""NP"">NP</option>"
                End If
            Case "OD"
                ' Doctor of Optometry, Oculus Doctor
                If InStr(CAPSADT, "OPTOMETRIST") > 0 Or InStr(CAPSADT, "OCULUS DOCTOR") > 0 Or (InStr(CAPSADT, "DOCTOR") > 0 And InStr(CAPSADT, "OPTOMETR") > 0) Then
                    results = "<option value=""OD"" selected>OD</option>"
                Else
                    results = "<option value=""OD"">OD</option>"
                End If
            Case "PA-C"
                If InStr(CAPSADT, "PA-C") > 0 Or InStr(CAPSADT, "PHYSICIAN ASSISTANT") > 0 Then
                    results = "<option value=""PA-C"" selected>PA-C</option>"
                Else
                    results = "<option value=""PA-C"">PA-C</option>"
                End If
            Case "PharmD"
                If InStr(CAPSADT, "PHARMD") > 0 Or InStr(CAPSADT, "PHARMACIST") > 0 Then
                    ' "OutPatient Pharmacy Supervisor" could be PharmD, not auto though
                    results = "<option value=""PharmD"" selected>PharmD</option>"
                Else
                    results = "<option value=""PharmD"">PharmD</option>"
                End If
            Case "PharmTech"
                If InStr(CAPSADT, "PHARMACY") > 0 And InStr(CAPSADT, "TECH") > 0 Then
                    ' "OutPatient Pharmacy Supervisor" could be PharmD, not auto though
                    results = "<option value=""PharmTech"" selected>PharmTech</option>"
                Else
                    results = "<option value=""PharmTech"">PharmTech</option>"
                End If
            Case "PhD"
                If CAPSADT = "PSYCHOLOGIST" Or InStr(CAPSADT, "PSYCHOLOGY") > 0 Then
                    results = "<option value=""PhD"" selected>PhD</option>"
                Else
                    results = "<option value=""PhD"">PhD</option>"
                End If
            Case "Psychiatrist"
                If CAPSADT = "PSYCHIATRIST" Or InStr(CAPSADT, "PSYCHIATRY") > 0 Then
                    results = "<option value=""Psychiatrist"" selected>Psychiatrist</option>"
                Else
                    results = "<option value=""Psychiatrist"">Psychiatrist</option>"
                End If
            Case "PT"
                If InStr(CAPSADT, "PHYSICAL") > 0 And InStr(CAPSADT, "THERAP") > 0 Then
                    results = "<option value=""PT"" selected>PT</option>"
                Else
                    results = "<option value=""PT"">PT</option>"
                End If
            Case "ST"
                ' see "Audiologist" for similar rules
                ' don't need to limit to ( InStr(CAPSADT,"THERAP")>0 or InStr(CAPSADT,"PATHOL")>0) )
                If InStr(CAPSADT, "SPEECH") > 0 Then
                    results = "<option value=""ST"" selected>ST</option>"
                Else
                    results = "<option value=""ST"">ST</option>"
                End If
            Case "RN"
                ' find fields that have inside them " RN" or "RN " but not "RN".
                ' example: "Nurse, R.N./Nursing Coordinator"
                If Left(CAPSADT, 2) = "RN" Or InStr(CAPSADT, " RN") > 0 Or InStr(CAPSADT, "RN ") > 0 Or InStr(CAPSADT, "REGISTERED NURSE") > 0 Then
                    results = "<option value=""RN"" selected>RN</option>"
                Else
                    results = "<option value=""RN"">RN</option>"
                End If
            Case "SW"
                If CAPSADT = "SW" Or CAPSADT = "SWS" Or InStr(CAPSADT, "SOCIAL WORKER") > 0 Then
                    results = "<option value=""SW"" selected>SW</option>"
                Else
                    results = "<option value=""SW"">SW</option>"
                End If
            Case "Staff"
                ' other various medical specialties that aren't MD, SW, PT, Psy etc
                ' future placeholder xxxxxxxxx for others that are identified to be "Staff"
                If InStr(CAPSADT, "xxxxxxxxxx") > 0 Then
                    results = "<option value=""Staff"" selected>Staff</option>"
                Else
                    results = "<option value=""Staff"">Staff</option>"
                End If
            Case "Sup"
                If InStr(CAPSADT, "SUPERVISOR") > 0 Then
                    results = "<option value=""Sup"" selected>Sup</option>"
                Else
                    results = "<option value=""Sup"">Sup</option>"
                End If
            Case "Tech"
                ' can't match "Health Tech" because some places use Health Tech as Clerk or PSA
                ' can't just use "Technician" as "Pharmacy Technician" would hit this too
                If InStr(CAPSADT, "HYGIENIST") > 0 Then
                    results = "<option value=""Tech"" selected>Tech</option>"
                Else
                    results = "<option value=""Tech"">Tech</option>"
                End If
            Case Else
                ' do not select one
                results = "<option value=""" & Replace(title, """", "&#34;") & """>" & title & "</option>"
        End Select
        If Not IsDBNull(desc) Then
            results = Replace(results, "</option>", " - " & desc & "</option>")
        End If
        CreateTitleOption = results
    End Function

    Sub ShowHTMLHeader()
        Dim favIconURL
        favIconURL = _clsMessageVAR.WebURL
        favIconURL = Replace(favIconURL, "Message.aspx", "favicon.ico")
        '  rel="icon" type="image/x-icon"
        '  rel="SHORTCUT ICON"
        '  rel="favicon.ico?"
        ' Prevent caching of the contents of the pages to local hard drive
        ' http://support.microsoft.com/kb/234067
        ' http://www.4guysfromrolla.com/webtech/111500-1.shtml
        ' Pragma: no-cache 
        '	- prevents caching only when used over a secure connection. 
        '	- is treated identically to Expires: -1 if used in a non-secure page, the page will be cached but marked as immediately expired. 
        ' Cache-Control: no-cache
        ' Cache-Control: no-store - intended to insruct a browser not to write it to disk
        '	- 

        Dim action, menu
        If (Not Request.QueryString("action") Is Nothing) Then
            action = Request.QueryString("action").ToString()
        Else
            action = ""
        End If

        If (Not Request.QueryString("menu") Is Nothing) Then
            menu = Request.QueryString("menu").ToString()
        Else
            menu = ""
        End If

        Response_WriteLine("<html>")
        Response_WriteLine("<head>")
        Response_WriteLine("<title>" & _clsMessageVAR.WebName & "</title>")
        Response_WriteLine("<meta http-equiv=""X-UA-Compatible"" content=""IE=Edge,chrome=1"">")
        Response_WriteLine("<meta name=""viewport"" content=""width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"">")
        Response_WriteLine("<meta name=""HandheldFriendly"" content=""true"">")
        Response_WriteLine("<link href=""css/bootstrap.css"" rel=""stylesheet"" media=""screen"">")
        Response_WriteLine("<link rel=""icon"" type=""image/ico"" href=""" & favIconURL & """>")
        Response_WriteLine("<link href=""" & favIconURL & """ rel=""SHORTCUT ICON"">")
        Response_WriteLine("<script src=""js/jquery-3.2.1.min.js"" type=""text/javascript""></script>")
        Response_WriteLine("<script src=""js/jquery-ui.js""></script>")
        Response_WriteLine("<script src=""js/bootstrap.min.js"" type=""text/javascript""></script>")
        Response_WriteLine("<script src=""js/jspdf.js"" type=""text/javascript""></script>")
        Response_WriteLine("<script language=""javascript"">")
        Response_WriteLine("			function disableCR13(evt) {")
        Response_WriteLine("			    evt = (evt) ? evt : ((window.event) ? window.event : """")")
        Response_WriteLine("			    if (evt) {")
        Response_WriteLine("			        if (evt.keyCode == 13 || evt.which==13 ) {")
        Response_WriteLine("			            return false;")
        Response_WriteLine("			        }")
        Response_WriteLine("			    }")
        Response_WriteLine("			}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"">")
        Response_WriteLine("			function showHint(evt,str,sit) {")
        Response_WriteLine("			    evt = (evt) ? evt : ((window.event) ? window.event : """")")
        Response_WriteLine("			    if (evt) {")
        Response_WriteLine("			        if (evt.keyCode == 13 || evt.which==13 ) {")
        Response_WriteLine("			            return false;")
        Response_WriteLine("			        }")
        Response_WriteLine("			    }")
        Response_WriteLine("				if (str.length == 0) { ")
        Response_WriteLine("					document.getElementById(""txtHint"").innerHTML = """";")
        Response_WriteLine("					return;")
        Response_WriteLine("				} else {")
        Response_WriteLine("				    if (str.length > 2) { ")
        Response_WriteLine("				        var ele = document.getElementsByName(""NameLookup"");")
        Response_WriteLine("				        for (i = 0; i < ele.length; i++) {")
        Response_WriteLine("				            if (ele[i].checked) {")
        Response_WriteLine("				                var radioVal = ele[i].value;")
        Response_WriteLine("				            }")
        Response_WriteLine("				        }")
        Response_WriteLine("					    var xmlhttp = new XMLHttpRequest();")
        Response_WriteLine("					    xmlhttp.onreadystatechange = function() {")
        Response_WriteLine("						    if (this.readyState == 4 && this.status == 200 && this.responseText != """") {")
        Response_WriteLine("							    document.getElementById(""txtHint"").innerHTML = this.responseText;")
        Response_WriteLine("						    }")
        Response_WriteLine("					    };")
        Response_WriteLine("					    xmlhttp.open(""GET"", ""gethint.aspx?q="" + str + ""&s="" + sit + ""&r="" + radioVal, false);")
        Response_WriteLine("					    xmlhttp.send();")
        Response_WriteLine("				    }")
        Response_WriteLine("				}")
        Response_WriteLine("			}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"">")
        Response_WriteLine("			function updateOverrides(str) {")
        Response_WriteLine("			    var  p1 =  document.getElementById(""Gl_overrideLName"").checked;")
        Response_WriteLine("			    var  p2 =  document.getElementById(""Gl_overrideFName"").checked;")
        Response_WriteLine("			    var  p3 =  document.getElementById(""Gl_overrideL4"").checked;")
        Response_WriteLine("			    var  p4 =  document.getElementById(""Gl_overridePhone"").checked;")
        Response_WriteLine("			    var  p5 =  document.getElementById(""Gl_overrideRCall"").checked;")
        Response_WriteLine("			    var  p6 =  document.getElementById(""Gl_overrideReason"").checked;")
        Response_WriteLine("			    var  p7 =  document.getElementById(""Gl_overrideComment"").checked;")
        Response_WriteLine("			    var  p8 =  document.getElementById(""Gl_overrideDOB"").checked;")
        Response_WriteLine("			    var  p9 =  document.getElementById(""Gl_overrideTeamColorize"").checked;")
        Response_WriteLine("		        var xmlhttp = new XMLHttpRequest();")
        Response_WriteLine("			    xmlhttp.onreadystatechange = function() {")
        Response_WriteLine("				    if (this.readyState == 4 && this.status == 200 && this.responseText != """") {")
        Response_WriteLine("				        alert(this.responseText);")
        Response_WriteLine("				    }")
        Response_WriteLine("			    };")
        Response_WriteLine("			    xmlhttp.open(""GET"", ""gethint.aspx?q="" + str + ""&p1="" + p1 + ""&p2="" + p2 + ""&p3="" + p3 + ""&p4="" + p4 + ""&p5="" + p5 + ""&p6="" + p6 + ""&p7="" + p7 + ""&p8="" + p8 + ""&p9="" + p9 + ""&r="" + str + ""&s="" + str, false);")
        Response_WriteLine("			    xmlhttp.send();")
        Response_WriteLine("			}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("    function GetQueryStringParams(sParam){")
        Response_WriteLine("        var sPageURL = window.location.search.substring(1);")
        Response_WriteLine("        var sURLVariables = sPageURL.split('&');")
        Response_WriteLine("        for (var i = 0; i < sURLVariables.length; i++){")
        Response_WriteLine("            var sParameterName = sURLVariables[i].split('=');")
        Response_WriteLine("            if (sParameterName[0] == sParam){")
        Response_WriteLine("                return sParameterName[1];")
        Response_WriteLine("            }")
        Response_WriteLine("        }")
        Response_WriteLine("    }")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("    $(document).ready(function() {")
        Response_WriteLine("        var refresh = GetQueryStringParams('refresh');")
        Response_WriteLine("        if (refresh == ""True""){")
        Response_WriteLine("            setTimeout(function() {window.location = window.location}, 300000);")
        Response_WriteLine("        }")
        Response_WriteLine("        $("":checkbox"").change(function (){")
        Response_WriteLine("            var sList = """";")
        Response_WriteLine("            $('input[type=checkbox]').each(function(){")
        Response_WriteLine("                var sThisVal = (this.checked ? this.id : """");")
        Response_WriteLine("                sList += (sThisVal=="""" ? """" : sThisVal + "", "");")
        Response_WriteLine("                $(""#ID_Sites"").val(sList.slice(0, -2));")
        Response_WriteLine("            });")
        Response_WriteLine("        }).change();")
        Response_WriteLine("        $(""#ID_Select"").change(function(){")
        Response_WriteLine("                var optionValue = $('#ID_Select').val();")
        Response_WriteLine("                if (optionValue == ""000"") {")
        Response_WriteLine("                    $("".box"").not(""."" + optionValue).hide();")
        Response_WriteLine("                    $(""."" + optionValue).show();")
        Response_WriteLine("                } else{")
        Response_WriteLine("                    $("".box"").hide();")
        Response_WriteLine("                }")
        Response_WriteLine("        }).change();")
        Response_WriteLine("    });")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("function enableDisableControls() {")
        Response_WriteLine("    var x = document.getElementById(""Report1"");")
        Response_WriteLine("    var y = document.getElementById(""Report2"");")
        Response_WriteLine("    var z = document.getElementById(""Report5"");")
        Response_WriteLine("    if (x.checked || y.checked){")
        Response_WriteLine("        document.getElementById(""idSuppressDetails"").disabled = false;")
        Response_WriteLine("    }")
        Response_WriteLine("    else{")
        Response_WriteLine("        document.getElementById(""idSuppressDetails"").disabled = true;")
        Response_WriteLine("    }")
        Response_WriteLine("    if (z.checked){")
        Response_WriteLine("        document.getElementById(""idStartDate"").disabled = true;")
        Response_WriteLine("        document.getElementById(""idEndDate"").disabled = true;")
        Response_WriteLine("        document.getElementById(""idReportReason"").disabled = false;")
        Response_WriteLine("    }")
        Response_WriteLine("    else{")
        Response_WriteLine("        document.getElementById(""idStartDate"").disabled = false;")
        Response_WriteLine("        document.getElementById(""idEndDate"").disabled = false;")
        Response_WriteLine("        document.getElementById(""idReportReason"").disabled = true;")
        Response_WriteLine("    }")
        Response_WriteLine("}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("function exportReportReasonTotals() {")
        Response_WriteLine("    var pdf = new jsPDF('p', 'pt', 'letter'),source = $('#Grid')[0],specialElementHandlers = {")
        Response_WriteLine("        '#bypassme': function(element, renderer){")
        Response_WriteLine("            return true;")
        Response_WriteLine("        }")
        Response_WriteLine("    }")
        Response_WriteLine("    margins = {")
        Response_WriteLine("    top: 20,")
        Response_WriteLine("    bottom: 60,")
        Response_WriteLine("    left: 60,")
        Response_WriteLine("    width: 522")
        Response_WriteLine("    };")
        Response_WriteLine("    pdf.fromHTML(source, margins.left, margins.top, {'width': margins.width, 'elementHandlers': specialElementHandlers},function (dispose) {pdf.save('ReportReasonTotals.pdf');},margins)")
        Response_WriteLine("}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("function exportReportCRWeekdaysC() {")
        Response_WriteLine("    var pdf = new jsPDF('p', 'pt', 'letter'),source = $('#Grid')[0],specialElementHandlers = {")
        Response_WriteLine("        '#bypassme': function(element, renderer){")
        Response_WriteLine("            return true;")
        Response_WriteLine("        }")
        Response_WriteLine("    }")
        Response_WriteLine("    margins = {")
        Response_WriteLine("    top: 20,")
        Response_WriteLine("    bottom: 60,")
        Response_WriteLine("    left: 60,")
        Response_WriteLine("    width: 522")
        Response_WriteLine("    };")
        Response_WriteLine("    pdf.fromHTML(source, margins.left, margins.top, {'width': margins.width, 'elementHandlers': specialElementHandlers},function (dispose) {pdf.save('ReportCompletionRate-Days-Consolidated.pdf');},margins)")
        Response_WriteLine("}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("function exportReportCRWeekdaysI() {")
        Response_WriteLine("    var pdf = new jsPDF('p', 'pt', 'letter'),source = $('#Grid')[0],specialElementHandlers = {")
        Response_WriteLine("        '#bypassme': function(element, renderer){")
        Response_WriteLine("            return true;")
        Response_WriteLine("        }")
        Response_WriteLine("    }")
        Response_WriteLine("    margins = {")
        Response_WriteLine("    top: 20,")
        Response_WriteLine("    bottom: 60,")
        Response_WriteLine("    left: 60,")
        Response_WriteLine("    width: 522")
        Response_WriteLine("    };")
        Response_WriteLine("    pdf.fromHTML(source, margins.left, margins.top, {'width': margins.width, 'elementHandlers': specialElementHandlers},function (dispose) {pdf.save('ReportCompletionRate-Days-Individual.pdf');},margins)")
        Response_WriteLine("}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("function exportReportCRHours() {")
        Response_WriteLine("    var pdf = new jsPDF('p', 'pt', 'letter'),source = $('#Grid')[0],specialElementHandlers = {")
        Response_WriteLine("        '#bypassme': function(element, renderer){")
        Response_WriteLine("            return true;")
        Response_WriteLine("        }")
        Response_WriteLine("    }")
        Response_WriteLine("    margins = {")
        Response_WriteLine("    top: 20,")
        Response_WriteLine("    bottom: 60,")
        Response_WriteLine("    left: 60,")
        Response_WriteLine("    width: 522")
        Response_WriteLine("    };")
        Response_WriteLine("    pdf.fromHTML(source, margins.left, margins.top, {'width': margins.width, 'elementHandlers': specialElementHandlers},function (dispose) {pdf.save('ReportCompletionRate-Hours.pdf');},margins)")
        Response_WriteLine("}")
        Response_WriteLine("</script>")
        Response_WriteLine("<script language=""javascript"" type=""text/javascript"">")
        Response_WriteLine("function exportReportMessageTotals() {")
        Response_WriteLine("    var pdf = new jsPDF('p', 'pt', 'letter'),source = $('#Grid')[0],specialElementHandlers = {")
        Response_WriteLine("        '#bypassme': function(element, renderer){")
        Response_WriteLine("            return true;")
        Response_WriteLine("        }")
        Response_WriteLine("    }")
        Response_WriteLine("    margins = {")
        Response_WriteLine("    top: 20,")
        Response_WriteLine("    bottom: 60,")
        Response_WriteLine("    left: 60,")
        Response_WriteLine("    width: 522")
        Response_WriteLine("    };")
        Response_WriteLine("    pdf.fromHTML(source, margins.left, margins.top, {'width': margins.width, 'elementHandlers': specialElementHandlers},function (dispose) {pdf.save('ReportMessageTotals.pdf');},margins)")
        Response_WriteLine("}")
        Response_WriteLine("</script>")
        Response_WriteLine("<!--		")
        Response_WriteLine("		<META HTTP-EQUIV=""Pragma"" CONTENT=""no-cache"">")
        Response_WriteLine("		<meta http-equiv=""Cache-Control"" CONTENT=""no-cache"">")
        Response_WriteLine("		<META HTTP-EQUIV=""Expires"" CONTENT=""-1"">")
        Response_WriteLine("-->")
        Response_WriteLine("	<style type=""text/css"">")
        Response_WriteLine("	.submitAsLink {")
        Response_WriteLine("		text-decoration:underline;")
        Response_WriteLine("		color:blue;")
        Response_WriteLine("		cursor:pointer; ")
        Response_WriteLine("	}")
        Response_WriteLine("	th, tr, td {")
        Response_WriteLine("		padding: 1px;")
        Response_WriteLine("		margin: 1px;")
        Response_WriteLine("	}")
        Response_WriteLine("	th {")
        Response_WriteLine("		background-color: #dbe4f0;")
        Response_WriteLine("	}")
        Response_WriteLine("	a {")
        Response_WriteLine("		color: #005baa;")
        Response_WriteLine("	}")
        Response_WriteLine("	a:hover {")
        Response_WriteLine("		color: #4f4a45;")
        Response_WriteLine("	}")
        Response_WriteLine("	.hover-item {")
        Response_WriteLine("	    background-color: red;")
        Response_WriteLine("	}")
        Response_WriteLine("	.hover-item: hover {")
        Response_WriteLine("	    background-color: red;")
        Response_WriteLine("	}")
        Response_WriteLine("	.hover-item-white a {")
        Response_WriteLine("	    color: white;")
        Response_WriteLine("	.hover-item-black a {")
        Response_WriteLine("	    color: black;")
        Response_WriteLine("	.box{")
        Response_WriteLine("	    color: #fff;")
        Response_WriteLine("	    padding: 20px;")
        Response_WriteLine("	    display: none;")
        Response_WriteLine("	    margin-top: 20px;")
        Response_WriteLine("	}")
        Response_WriteLine("	.000{ background: #ff0000; }")
        Response_WriteLine("	</style>")
        Response_WriteLine("	</head>")
        Response_WriteLine("	<body style=""margin:0;background-color:#eeeeee;color:#00007d;"">")
        Response_WriteLine("	<center>")
        Response_WriteLine("	<noscript>")
        Response_WriteLine("		<p><big><b><font color=""red"">Warning, a browser that supports javascript is required.<br>")
        Response_WriteLine("		Contact the IT department to fix Active Scripting.</font></b></big></p>")
        Response_WriteLine("	</noscript>")
        Response_WriteLine("	<table bgcolor=""#d6dbe9"" width=""100%""><tr><td><center>")
        ' menu from "webURL" has no AdminAccess levels looked up
        ' menu from "webAdminURL" has AdminAccess levels granted from database settings

        If Me.UserName <> "None" Then
            Dim tmpDate As DateTime
            tmpDate = DateTime.Now.AddHours(dTimezoneOffset)
            Response_WriteLine("<div id=""titlebar"">")
            Response_WriteLine("<table id=""thead"" width=""100%"" cellspacing=""0"" border=""0"">")
            Response_WriteLine("<tr>")
            Response_WriteLine("<td align=""left""><font color=""#eeeeee""><i>" & _clsMessageVAR.WebName & "</i></font></td>")
            Response_WriteLine("<td align=""center""><font color=""#eeeeee""><i>" & Me.CleanUserName(Me.UserName) & "&nbsp;" & Me.ShowTitle & "</i></font></td>")
            Response_WriteLine("<td align=""right""><font color=""#eeeeee""><i>" & tmpDate.ToLongDateString() & "</i></font></td>")
            Response_WriteLine("</tr>")
            Response_WriteLine("</table>")
            Response_WriteLine("</div>")
            'Response_WriteLine("" & Me.CleanUserName(Me.UserName) & "&nbsp;" & Me.ShowTitle & "")
        End If

        Select Case A
            Case "Admin"
                Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #d6dbe9;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""navbar-header"">")
                Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
                Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("</button>")
                Response_WriteLine("<a class=""navbar-brand"" href=""" & _clsMessageVAR.WebURL & """><b><i>Home</i></b></a>")
                Response_WriteLine("</div>")
                Response_WriteLine("<div class=""navbar-collapse collapse"">")
                Response_WriteLine("<ul class=""nav navbar-nav"">")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebURL & """>New Message</a></li>")
                ' catch old email links "MessageAdmin/Message.aspx?A=Admin&S=607&I=158830" and correct the menu value
                If A = "Admin" And menu = "" Then    ' and I <> "" 0 then
                    menu = "Open"
                End If

                ' Messages broken up menu
                If menu = "Search" Or menu = "MySent" Or menu = "Open" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=Search&S=" & S & "&action=" & action & """>")
                    If menu = "Search" Then
                        Response_WriteLine("<big><b>Search</b></big>")
                    Else
                        Response_WriteLine("Search")
                    End If
                    Response_WriteLine("</a></li>")
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=MySent&S=" & S & "&action=" & action & """>")
                    If menu = "MySent" Then
                        Response_WriteLine("<big><b>My Sent</b></big>")
                    Else
                        Response_WriteLine("My Sent")
                    End If
                    Response_WriteLine("</a></li>")
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=Open&refresh=True&S=" & S & "&action=" & action & """>")
                    If menu = "Open" Then
                        Response_WriteLine("<big><b>Open</b></big>")
                    Else
                        Response_WriteLine("Open")
                    End If
                    Response_WriteLine("</a></li>")
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Admin&S=" & S & """>Admin Menu</a></li>")
                Else
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&refresh=True&S=" & S & "&action=All"">Messages</a></li>")
                End If

                If menu = "Admin" Or menu = "History" Or menu = "Audit" Or menu = "Reports" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Admin&S=" & S & """><big><b>Admin Menu</b></big></a></li>")
                End If


                ' only show Setup Menu if AdminAccess allows it
                If Me.AdminAccess = "Admin" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&menu=Admin&S=" & S & """>")
                    If A = "Setup" Then
                        Response_WriteLine("<big><b>Setup Menu</b></big>")
                    Else
                        Response_WriteLine("Setup Menu")
                    End If
                    Response_WriteLine("</a></li>")
                End If

                If menu = "Help" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Help&S=" & S & """><big><b>Help</b></big></a></li>")
                Else
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Help&S=" & S & """>Help</a></li>")
                End If
                Response_WriteLine("</ul></div></div></nav>")
            Case "Setup"
                Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #d6dbe9;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""navbar-header"">")
                Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
                Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("</button>")
                Response_WriteLine("<a class=""navbar-brand"" href=""" & _clsMessageVAR.WebURL & """><b><i>Home</i></b></a>")
                Response_WriteLine("</div>")
                Response_WriteLine("<div class=""navbar-collapse collapse"">")
                Response_WriteLine("<ul class=""nav navbar-nav"">")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebURL & """>New Message</a></li>")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&S=" & S & "&action=All"">Messages</a></li>")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Admin&S=" & S & """>Admin Menu</a></li>")
                If menu = "Help" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & """>Setup Menu</a></li>")
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&menu=Help&S=" & S & """><big><b>Help</b></big></a></li>")
                    Response_WriteLine("</ul>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</nav>")
                Else
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & """><big><b>Setup Menu</b></big></a></li>")
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&menu=Help&S=" & S & """>Help</a></li>")
                    Response_WriteLine("</ul>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</nav>")
                End If


            Case "Help"
                ' entry into Help from "webURL"
                ' no AdminAccess levels 
                Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #d6dbe9;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""navbar-header"">")
                Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
                Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("</button>")
                Response_WriteLine("<a class=""navbar-brand"" href=""" & _clsMessageVAR.WebURL & """><b><i>Home</i></b></a>")
                Response_WriteLine("</div>")
                Response_WriteLine("<div class=""navbar-collapse collapse"">")
                Response_WriteLine("<ul class=""nav navbar-nav"">")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebURL & """>New Message</a></li>")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&S=" & S & "&action=All"">Messages</a></li>")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Admin&S=" & S & """>Admin Menu</a></li>")
                If menu = "Setup" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Help&menu=" & menu & "&S=" & S & """><big><b>Help</b></big></a></li>")
                    Response_WriteLine("</ul>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</nav>")
                Else
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebURL & "?A=Help&S=" & S & """><big><b>Help</b></big></a></li>")
                    Response_WriteLine("</ul>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</nav>")
                End If



            Case Else

                ' A = ""
                ' New Message screen has a simplified Admin Menu that defaults into "Open Messages"
                ' no Admin or Setup menu shown
                ' open message Action is determined to be All, My, Team depending on level of username memberships
                Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #d6dbe9;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""navbar-header"">")
                Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
                Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("<span class=""icon-bar""></span>")
                Response_WriteLine("</button>")
                Response_WriteLine("<a class=""navbar-brand"" href=""" & _clsMessageVAR.WebURL & """><b><i>Home</i></b></a>")
                Response_WriteLine("</div>")
                Response_WriteLine("<div class=""navbar-collapse collapse"">")
                Response_WriteLine("<ul class=""nav navbar-nav"">")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebURL & """><big><b>New Message</b></big></a></li>")
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&refresh=True&S=" & S & """>Messages</a></li>")
                If menu = "Admin" Or menu = "Setup" Then
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Help&menu=" & menu & "&S=" & S & """><big><b>Help</b></big></a></li>")
                    Response_WriteLine("</ul>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</nav>")
                Else
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebURL & "?A=Help&S=" & S & """>Help</a></li>")
                    Response_WriteLine("</ul>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</nav>")
                End If



        End Select ' Case A

        If S = "0" Or S = "" Then
            ' display nothing
            ' Response.Write("Site: Not Chosen")
        Else
            Response_WriteLine("<i>" & S & " - " & Me.SiteName & "</i>")
        End If


        If Me.IsHoliday(theDate) <> "" Then
            Response_WriteLine("<br/>" & Me.IsHoliday(theDate) & "")
        End If
        Response_WriteLine("</center></td></tr></table>")
    End Sub

    Sub ShowHTMLFooter()
        ' If you're really serious about the Pragma working, place another  of HEAD tags at the bottom of the document, 
        ' before the end HTML tag and re-enter the Pragma. This is a suggestion straight from Microsoft Support.

        ' used to calculate and show page load times
        '   pageStartTime initialized upon initial code load
        Dim diff
        diff = Vb6.Timer() - Me.PageStartTime
        If diff > 20 Then
            ' too slow!
            '  the Application variable to indicate the time of this.
            ' MM web page can disable certain task intensive features while timeout phase is in play	
            Application.Lock()
            Application("TIMEOUT") = Now()
            Application.UnLock()
        End If
        ' round to .1 seconds for nice display
        diff = FormatNumber(diff, 1)
        Response_WriteLine("<div><font color=""#eeeeee"">Page Load Time = " & diff & " seconds")
        If _clsMessageVAR.BUsesSqlString = True Then
            Response_WriteLine("on SQL.")
        Else
            Response_WriteLine("on MS Access.")
        End If

        ' diff is now the number of seconds since the sSqlString timeout or > 20 second page load
        diff = Me.SecSinceOverload()
        Select Case diff
            Case -3
                Response_WriteLine("<br>Timeout not initialized")
            Case -2
                Response_WriteLine("<br>Timout not a date value")
            Case -1
                Response_WriteLine("<br>No Timeout since Application Started")
            Case Else
                Response_WriteLine("<br>" & diff & " seconds since last Timeout.")
                If diff >= 0 And diff < 1800 Then
                    Response_WriteLine("Server is under heavy load, some features have been streamlined")
                End If
        End Select
        Response_WriteLine("<br><font color=""#1E1E8B"">Version 26.2.20</font>")
        Response_WriteLine("</font></div>")
        Response_WriteLine("</center>")
        Response_WriteLine("</body>")
        Response_WriteLine("<!--")
        Response_WriteLine("<HEAD>")
        Response_WriteLine("<META HTTP-EQUIV=""Pragma"" CONTENT=""no-cache"">")
        Response_WriteLine("<meta http-equiv=""Cache-Control"" CONTENT=""no-cache"">")
        Response_WriteLine("<META HTTP-EQUIV=""Expires"" CONTENT=""-1"">")
        Response_WriteLine("</HEAD>")
        Response_WriteLine("-->")
        Response_WriteLine("</html>")
    End Sub

    Sub ShowHelp()

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        'Response_WriteLine("<br>")
        Response_WriteLine("<div class=""container-fluid"">")
        Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
        Response_WriteLine("<table>")
        Response_WriteLine("<tr><td colspan=""2""><h3>Guides</h3></td></tr>")
        Select Case _clsMessageVAR.WebName
            Case "VISN 12 Phone Message Manager" ' Add a link for VISN 12 SharePoint 6/15/2024
                Response_WriteLine("<tr><td width=""40"">&nbsp;</td><td>")
                Response_WriteLine("<a href=""https://dvagov.sharepoint.com/sites/VISN12TelecomCiscoJabberFinesse/SitePages/Phone-Message-Manager.aspx?source=https%3A%2F%2Fdvagov.sharepoint.com%2Fsites%2FVISN12TelecomCiscoJabberFinesse%2FSitePages%2FForms%2FByAuthor.aspx/"">VISN 12 Phone Message Manager Resources (sharepoint.com)</a> Training resources and site champions</td></tr>")
            Case "VISN 23 Phone Message Manager" ' Add a link for VISN 23 SharePoint 8/29/2025
                Response_WriteLine("<tr><td width=""40"">&nbsp;</td><td>")
                Response_WriteLine("<a href=""https://dvagov.sharepoint.com/sites/vhavisn23vahealthconnect/SitePages/V23-Message-Manager.aspx"">VISN 23 Phone Message Manager Resources (sharepoint.com)</a> Training resources and site champions</td></tr>")
                Response_WriteLine("<br>")
                Response_WriteLine("<tr><td colspan=""2""><h3>System Color Codes</h3></td></tr>")
                Response_WriteLine("<tr><td colspan=""2""><img align=""left"" alt=""Reason Colors"" name=""Reason Colors"" src=""images/ColorLegend.png""></img></td></tr>")
                Response_WriteLine("<br>")
            Case Else
                Response_WriteLine("<tr><td width=""40"">&nbsp;</td><td>")
                Response_WriteLine("<a href=""" & Replace(_clsMessageVAR.WebURL, "message.aspx", "Help/Phone Message Manager - Site Champions.docx") & """>Phone Message Manager - Site Champions.docx</a> Team setup adjustments should be directed to the Site Champion</td></tr>")
                ' All other PMMs get link to Site Champions document vs. SharePoint
        End Select
        If Me.AdminAccess = "Admin" Then
            ' "Admin" = show Admin Guide too
            ' "Site" = do not show admin guide
            ' "Member" = do not show admin guide
            Response_WriteLine("<tr><td width= ""40"">&nbsp;</td><td>")
            Response_WriteLine("<a href=""" & Replace(_clsMessageVAR.WebAdminURL, "message.aspx", "Phone Message Manager - Admin Guide.docx") & """>Phone Message Manager - Admin Guide.docx</a> How To create And edit teams</td></tr>")
        End If
        Response_WriteLine("<tr><td colspan=""2""><h3>Secure Messaging patient To provider</h3></td></tr>")
        Response_WriteLine("<tr><td width=""40"">&nbsp;</td><td>")
        Response_WriteLine("<a href=""https://www.va.gov/health-care/manage-health/"">My HealtheVet</a>  Ask patients and providers if they have My HealtheVet accounts.<br>")
        Response_WriteLine("<br>")
        Response_WriteLine("Both parties to sign up and then they can do secure communications within My HealtheVet.<br>")
        Response_WriteLine("See the My HealtheVet <a href=""https://www.myhealth.va.gov/mhv-portal-web/faqs"">FAQ</a> ")
        Response_WriteLine("for information on this feature.")
        Response_WriteLine("</td></tr>")
        Response_WriteLine("<tr><td colspan=""2"">&nbsp;</td></tr>")
        Response_WriteLine("<tr><td colspan=""2""><h3>Entry Shortcuts</h3></td></tr>")
        Response_WriteLine("<tr><td width=""40"">&nbsp;</td><td>")
        Response_WriteLine("<p>Make one of these a favorite if you need to enter the form with the Site or Location auto-selected.")
        Response_WriteLine("Save time on the repetitive task of clicking submit.</p>")
        Dim lastSiteNum
        lastSiteNum = ""

        MyCommand.CommandText = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Locations.Lo_Index, tab_Locations.Lo_Name FROM tab_Locations" & " LEFT JOIN tab_Sites ON tab_Locations.Lo_SiteNum = tab_Sites.Si_SiteNum" & " WHERE tab_Sites.Si_Active='Yes' AND tab_Locations.Lo_Active='Yes'" & " ORDER BY tab_Sites.Si_SiteOrder, tab_Locations.Lo_SortOrder;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            Response_WriteLine("<table>")

            While sqlDataReader.Read = True
                If lastSiteNum <> sqlDataReader.Item("Si_SiteNum") Then
                    Response_WriteLine("<tr><td><a href=""" & _clsMessageVAR.WebURL & "?S=" & sqlDataReader.Item("Si_SiteNum") & """>" & sqlDataReader.Item("Si_Name") & "</a></td></tr>")
                    lastSiteNum = sqlDataReader.Item("Si_SiteNum")
                End If
                Response_WriteLine("<tr><td><a href=""" & _clsMessageVAR.WebURL & "?S=" & sqlDataReader.Item("Si_SiteNum") & "&L=" & sqlDataReader.Item("Lo_Index") & """>" & sqlDataReader.Item("Si_Name") & " - " & sqlDataReader.Item("Lo_Name") & "</a></td></tr>")
            End While

            Response_WriteLine("</table>")

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        Response_WriteLine("</td></tr>")
        Response_WriteLine("</table>")
        Response_WriteLine("</div>")
        Response_WriteLine("</div>")
    End Sub

    ' first entry
    Sub ShowMainMenu()
        ' phase 1 = site
        ' phase 2 = location
        ' phase 3 = member and the message

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim isSingleSite
        Dim isSingleLocation

        Dim errorfound
        errorfound = ""
        ' ensure Site is Active
        If S <> "" Then
            MyCommand.CommandText = "SELECT tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & S & "';"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    System.Web.HttpContext.Current.Session(“Oops”) = "*** No record found for site - " & S & " ***"
                Else
                    sqlDataReader.Read()

                    If sqlDataReader.Item("Si_Active") <> "Yes" Then
                        System.Web.HttpContext.Current.Session(“Oops”) = "*** Site '" & sqlDataReader.Item("Si_Name") & "' is not active ***"
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If

        ' ensure Location is Active
        If L <> "" Then
            MyCommand.CommandText = "SELECT tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations WHERE tab_Locations.Lo_Index = " & L & ";"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    System.Web.HttpContext.Current.Session(“Oops”) = "*** No record found for location - " & L & " ***"
                Else
                    sqlDataReader.Read()

                    If sqlDataReader.Item("Lo_Active") <> "Yes" Then
                        System.Web.HttpContext.Current.Session(“Oops”) = "*** Location '" & sqlDataReader.Item("Lo_Name") & "' is not active ***"
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If

        ' check for mismatched Site / Location entry
        If S <> "" And L <> "" Then
            MyCommand.CommandText = "SELECT tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & S & "' AND tab_Locations.Lo_Index = " & L & ";"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    System.Web.HttpContext.Current.Session(“Oops”) = "*** ERROR - Location '" & Me.GetLocationName(L) & "' is not a member of Site " & Me.GetSiteName(S) & " ***"
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        End If

        If System.Web.HttpContext.Current.Session(“Oops”) = "" Then
            If Me.Whatsite = "" Then
                ' form not completed yet
                isSingleSite = Me.SingleSite()
                If isSingleSite = "000" Then
                    ' Multiple sites
                    If S = "" Then
                        ' multiple sites, start with Menu1
                        Me.ShowMainMenu1()
                    Else
                        ' multiple sites, but S valid
                        Me.Whatsite = S
                        If L = "" Then
                            ' S valid, L is not - so default the Site to the querystring value
                            isSingleLocation = Me.SingleLocation()
                            If isSingleLocation = 0 Then
                                ' multiples to pick from
                                Me.ShowMainMenu2()
                            Else
                                ' even though L not pre-selected, there is only one, so jump to Menu3
                                Me.Whatlocation = isSingleLocation
                                Me.ShowMainMenu3()
                            End If
                        Else
                            ' L chosen
                            ' S valid, L valid - default the Location to the querystring value
                            Me.Whatlocation = L
                            Me.ShowMainMenu3()
                        End If
                    End If
                Else
                    ' single site.  skip menu1, go to menu2
                    Me.Whatsite = isSingleSite
                    If L = "" Then
                        ' L not valid 
                        ' SingleLocation() requires "whatsite" value
                        isSingleLocation = Me.SingleLocation()
                        If isSingleLocation = 0 Then
                            ' multiples to pick from
                            Me.ShowMainMenu2()
                        Else
                            ' single location.  skip menu2, go to menu3
                            Me.Whatlocation = isSingleLocation
                            Me.ShowMainMenu3()
                        End If
                    Else
                        ' L valid - default the Location to the querystring value
                        Me.Whatlocation = L
                        Me.ShowMainMenu3()
                    End If
                End If
            Else
                ' one of the forms have been submitted
                Select Case Request.Form("form_Phase")
                    Case "Phase1"
                        ' SingleLocation() requires "whatsite" value
                        isSingleLocation = Me.SingleLocation()
                        If isSingleLocation = 0 Then
                            ' multiples to pick from
                            Me.ShowMainMenu2()
                        Else
                            ' single location.  skip menu2, go to menu3
                            Me.Whatlocation = isSingleLocation
                            Me.ShowMainMenu3()
                        End If
                    Case "Phase2"
                        Me.ShowMainMenu3()
                    Case "Clone"
                        ' FEE can clone a submitted message to pre-fill vendor fields
                        ' PACT can clone a submitted message to pre-fill patient fields
                        Me.ShowMainMenuClone()
                    Case "Phase3"
                        Me.Process()
                    Case Else
                        Response_WriteLine("<p><font color=red><big><b>Error</b></big></font> - Unknown State.<br>")
                        Response_WriteLine("<br>")
                        Response_WriteLine("Please <A HREF=""" & _clsMessageVAR.WebURL & """>Start Over</a>.</p>")
                End Select
            End If
        Else
            Response_WriteLine("<p><font color=""red"">" & errorfound & "")
            Response_WriteLine("Please <a href=""" & _clsMessageVAR.WebURL & """>Start Over</a>.</font></p>")
        End If ' errorfound
    End Sub

    ' PHASE 1
    Sub ShowMainMenu1()
        ' phase 1 = site
        ' phase 2 = location
        ' phase 3 = member and the message
        Dim width As Long = 0


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        MyCommand.CommandText = "SELECT tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes' ORDER BY tab_Sites.Si_SiteOrder;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            While sqlDataReader.Read = True
                If Len(sqlDataReader.Item("Si_Name")) > width Then
                    width = Len(sqlDataReader.Item("Si_Name"))
                End If
            End While

            ' convert from characters to pixels
            width = width * 10
            If width < 72 Then
                width = 72
            End If
            If width > 720 Then
                width = 720
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        MyCommand.CommandText = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes' ORDER BY tab_Sites.Si_SiteOrder;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            Response_WriteLine("<div class=""container-fluid"">")
            Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
            Response_WriteLine("<p>")
            Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
            Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><font size=""5""><b>" & _clsMessageVAR.WebName & "</b></font></center></td></tr>")
            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
            Response_WriteLine("<tr><td bgcolor = ""#eeeeee"" align=""right"" valign=""top"">Member Lookup&nbsp;<input type = ""radio"" name=""NameLookup"" value=""MEMBER"" checked></td><td bgcolor=""#eeeeee"">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Team Lookup&nbsp;<input type=""radio"" value=""TEAM"" name=""NameLookup""> ")
            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Name:&nbsp;</td><td bgcolor=""#eeeeee"">")
            Response_WriteLine("<form><input type=""text"" class=""form-control"" style=""width: 135px;"" size=""15"" maxlength=""255"" onKeyPress=""return disableCR13(event)"" onKeyUp=""return showHint(event,this.value,'0')""></form></td></tr>")
            Response_WriteLine("<p>")
            Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
            Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
            Response_WriteLine("<tr><td><p><span id=""txtHint"" style=""color: #777777; font-size: 10pt""></span></p></td></tr>")
            Response_WriteLine("</table>")
            Response_WriteLine("</table>")
            Response_WriteLine("</p>")
            Response_WriteLine("</table>")
            Response_WriteLine("</table>")
            Response_WriteLine("</p>")
            Response_WriteLine("<p>")
            Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
            Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Or Choose Site to continue: &nbsp;</td><td bgcolor=""#eeeeee""> ")

            If Not sqlDataReader.HasRows Then
                Response_WriteLine("<p>")
                Response_WriteLine("<font color=red>Error - No Sites are active</font><br>")
                Response_WriteLine("<br>")
                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and try again.")
                Response_WriteLine("</p>")
                Response_WriteLine("<div />")
                Response_WriteLine("<div />")
            Else
                While sqlDataReader.Read = True
                    Response_WriteLine("<form name=""frmMessage" & sqlDataReader.Item("Si_SiteNum") & """ method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:4;margin-bottom:4"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes""> ")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Phase1""> ")
                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & sqlDataReader.Item("Si_SiteNum") & """> ")
                    Response_WriteLine("<input type=""submit"" name=""form_Submit" & sqlDataReader.Item("Si_SiteNum") & """ class=""btn btn-primary"" value=""" & Replace(sqlDataReader.Item("Si_Name"), """", "&#34;") & """ style=""width:" & width & ";font-size:14"">")
                    Response_WriteLine("</form>")
                End While
            End If

            Response_WriteLine("</td></tr></table></table>")
            Response_WriteLine("</p>")
            Response_WriteLine("<div />")
            Response_WriteLine("<div />")

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try
    End Sub

    ' PHASE 2
    Sub ShowMainMenu2()
        ' phase 1 = site
        ' phase 2 = location (Location)
        ' phase 3 = member and the message
        Dim width

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        width = 0

        MyCommand.CommandText = "SELECT tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & Me.Whatsite & "' AND tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SortOrder;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            While sqlDataReader.Read = True
                If Len(sqlDataReader.Item("Lo_Name")) > width Then
                    width = Len(sqlDataReader.Item("Lo_Name"))
                End If
            End While

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        ' convert from characters to pixels
        width = width * 10
        If width < 72 Then
            width = 72
        End If
        If width > 720 Then
            width = 720
        End If

        MyCommand.CommandText = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & Me.Whatsite & "' AND tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SortOrder;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                Response_WriteLine("<p>")
                Response_WriteLine("<font color=red>Error - No locations are active for this site</font><br>")
                Response_WriteLine("<br>")
                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and try again.")
                Response_WriteLine("</p>")
            Else
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
                Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><font size=""5""><b>" & _clsMessageVAR.WebName & "</b></font></center></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor = ""#eeeeee"" align=""right"" valign=""top"">Member Lookup&nbsp;<input type = ""radio"" name=""NameLookup"" value=""MEMBER"" checked></td><td bgcolor=""#eeeeee"">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Team Lookup&nbsp;<input type=""radio"" value=""TEAM"" name=""NameLookup""> ")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Name:&nbsp;</td><td bgcolor=""#eeeeee"">")
                Response_WriteLine("<form><input type=""text"" class=""form-control"" style=""width: 135px;"" size=""15"" maxlength=""255"" onKeyPress=""return disableCR13(event)"" onKeyUp=""return showHint(event,this.value,'" & Me.Whatsite & "')""></form></td></tr>")
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
                Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
                Response_WriteLine("<tr><td><p><span id=""txtHint"" style=""color: #777777; font-size: 10pt""></span></p></td></tr>")
                Response_WriteLine("</table>")
                Response_WriteLine("</table>")
                Response_WriteLine("</p>")
                Response_WriteLine("</table>")
                Response_WriteLine("</table>")
                Response_WriteLine("</p>")
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
                Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center>Or Choose Location to Continue</center></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Site</td><td bgcolor=""#eeeeee"">&nbsp;" & Me.Whatsite & "&nbsp;" & Me.GetSiteName(Me.Whatsite) & "</td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Location: &nbsp;</td><td bgcolor=""#eeeeee"">")
                While sqlDataReader.Read = True
                    Response_WriteLine("<form name=""frmMessage" & sqlDataReader.Item("Lo_Index") & """ method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:4;margin-bottom:4"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Phase2"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & sqlDataReader.Item("Lo_Index") & """>")
                    Response_WriteLine("<input type=""submit"" name=""form_Submit" & sqlDataReader.Item("Lo_Index") & """ class=""btn btn-primary"" value=""" & Replace(sqlDataReader.Item("Lo_Name"), """", "&#34;") & """ style=""width:" & width & ";font-size:14"">")
                    Response_WriteLine("</form>")
                End While
                Response_WriteLine("</td></tr></table></table>")
                Response_WriteLine("</p>")
                Response_WriteLine("</div></div>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    ' PHASE 3
    Sub ShowMainMenu3()
        ' phase 1 = site
        ' phase 2 = location
        ' phase 3 = member and the message
        Dim sSqlString, bFound
        Dim Teamradio, isSingleTeam, namelistfull, namelist, MessageType
        Dim sTeamIndex As String

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text
        ' LocationIndex = the ShowMainMenu2 reponse.

        If (Not Request.QueryString("T") Is Nothing) Then
            sTeamIndex = Request.QueryString("T").ToString()
            MyCommand.CommandText = "SELECT * FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & Me.Whatlocation & " AND tab_Teams.Te_Index = " & sTeamIndex & ";"
            isSingleTeam = CInt(sTeamIndex)
        Else
            sTeamIndex = ""
            MyCommand.CommandText = "Select * FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & Me.Whatlocation & " And tab_Teams.Te_Active = 'Yes' ORDER BY tab_Teams.Te_SortOrder;"
            isSingleTeam = Me.SingleTeam(Me.Whatlocation)
        End If

        MessageType = Me.GetTypeFromLocationIndex(Me.Whatlocation)

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If
            'Response.Write(MyCommand.CommandText)
            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                bFound = False
            Else
                bFound = True

                Teamradio = "<div class=""radio"">"
                While sqlDataReader.Read = True
                    ' every row is a table 
                    ' - in order for the "idDivT" to inherit the width of the <td> instead of inheriting the width of the line
                    ' - in order for each "namelist" to flow immediately after the team name instead of column aligned
                    Teamradio = Teamradio & "<table><tr>"

                    namelistfull = Me.GetTeamMemberNames(sqlDataReader.Item("Te_Index"), True, False)
                    If namelistfull = "" Then
                        ' guaranteed to be Nothing anyway, save a database lookup
                        namelist = ""
                    Else
                        namelist = Me.GetTeamMemberNames(sqlDataReader.Item("Te_Index"), False, False)
                    End If

                    Teamradio = Teamradio & "<td valign=""top"">"
                    Teamradio = Teamradio & "<p onmouseover=""javascript:idDivT" & sqlDataReader.Item("Te_Index") & ".style.display='block';"""
                    Teamradio = Teamradio & " onmouseout=""javascript:idDivT" & sqlDataReader.Item("Te_Index") & ".style.display='none';"">"
                    Teamradio = Teamradio & "&nbsp;&nbsp;&nbsp;<input type=""radio"" name=""form_TeamIndex"" id=""idTeam"" value=""" & sqlDataReader.Item("Te_Index") & """"
                    If isSingleTeam <> 0 Then
                        Teamradio = Teamradio & """ checked>"
                    Else
                        Teamradio = Teamradio & """>"
                    End If
                    Teamradio = Teamradio & "&nbsp;</p>"
                    Teamradio = Teamradio & "</td>"

                    Teamradio = Teamradio & "<td valign=""top"" width=""100%"">"
                    If namelistfull <> "" And namelistfull <> namelist Then
                        ' hover over to see the Complete List of members, regarless of ShowOn setting
                        Teamradio = Teamradio & "<div id=""idDivT" & sqlDataReader.Item("Te_Index")
                        Teamradio = Teamradio & """ style=""display:none;position:absolute;border-style:solid;border-color:navy;border-width:1;background-color:white;color:navy;padding:6px;z-index:100"">"
                        Teamradio = Teamradio & sqlDataReader.Item("Te_Name") & " - " & namelistfull & "</div>"
                    Else
                        ' Nothing div so javascript won't error from missing div id
                        Teamradio = Teamradio & "<div id=""idDivT" & sqlDataReader.Item("Te_Index") & """ style=""display:none;position:absolute;""></div>"
                    End If
                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                        Teamradio = Teamradio & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name"))
                    Else
                        Teamradio = Teamradio & Me.ColorizeFont(sqlDataReader.Item("Te_Name"))
                    End If

                    ' always show the "showOn" members	
                    If namelist <> "" Then
                        ' show the ShowOn names
                        Teamradio = Teamradio & " - " & namelist
                    End If
                    Teamradio = Teamradio & "</td>"

                    Teamradio = Teamradio & "</tr></table>" & vbCrLf & "<br />"
                End While
                Teamradio = Teamradio & "</div>"

                Response_WriteLine("<br/>")
                Response_WriteLine("<p>")
                Response_WriteLine("<table><tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor = ""#eeeeee"" align=""right"" valign=""top"">Member Lookup&nbsp;<input type = ""radio"" name=""NameLookup"" value=""MEMBER"" checked></td><td bgcolor=""#eeeeee"">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Team Lookup&nbsp;<input type=""radio"" value=""TEAM"" name=""NameLookup""> ")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Name:&nbsp;</td><td bgcolor=""#eeeeee"">")
                Response_WriteLine("<form><input type=""text"" class=""form-control"" style=""width: 135px;"" size=""15"" maxlength=""255"" onKeyPress=""return disableCR13(event)"" onKeyUp=""return showHint(event,this.value,'" & Me.Whatsite & "')""></form></td></tr></table>")
                Response_WriteLine("</p>")
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" style=""border: 1px solid #eeeeee;""><tr><td>")
                Response_WriteLine("<table cellpadding=""3"" cellspacing=""0"">")
                Response_WriteLine("<tr><td><p><span id=""txtHint"" style=""color: #777777; font-size: 10pt""></span></p></td></tr>")
                Response_WriteLine("</table>")
                Response_WriteLine("</table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        If bFound = True Then

            Dim reasonrs, ReasonRadio, ReturnRadio
            Dim SUBMITCOUNT, FLAGCOUNT, bREMINDER
            Dim sec



            Select Case MessageType
                Case "PACT"
                    ' PACT does not have Vendor fields

                    ReasonRadio = "<select name=""form_Reason"" id=""idReason"" class=""form-control"" onblur=""javascript:ShowMedChoice();"">" & vbCrLf & "<option value="""" selected></option>" & vbCrLf

                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()

                    MyCommand.CommandText = "SELECT tab_Reasons.Re_Name FROM tab_Reasons WHERE tab_Reasons.Re_Type = 'PACT'" & " AND tab_Reasons.Re_Active = 'Yes' ORDER BY tab_Reasons.Re_SortOrder;"

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        While sqlDataReader.Read = True
                            ' replace " with encoded quote character 
                            ' single apostrophe ' = &#39;
                            ' quote " = &#34;
                            ' Replace(reasonrs("Re_Name"),"""","&#34;")
                            ' alternate method would need a DECODE after submit, before can use it:  Server.URLEncode(reasonrs("Re_Name"))
                            ReasonRadio = ReasonRadio & "<option " & ReconcileReasonInlineStyle(sqlDataReader.Item("Re_Name")) & " value=""" & Replace(sqlDataReader.Item("Re_Name"), """", "&#34;") & """>" & sqlDataReader.Item("Re_Name") & "</option>" & vbCrLf
                        End While

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ReasonRadio = ReasonRadio & "</select>" & vbCrLf

                    ' event=onchange:
                    '   annoying for using arrow keys to drop down to the selection as it jumps out at first arrow key.
                    '   best to do it with onblur as that's when the item loses focus.
                    ReturnRadio = "<select name=""form_ReturnCall"" id=""idReturnCall"" class=""form-control"" onblur=""javascript:ShowBestTime();"">" & "<option value="""" selected></option>" & "<option value=""No"">No</option>" & "<option value=""Yes"">Yes</option>" & "</select>"
                    Response_WriteLine("<div class=""container-fluid"">")
                    Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                    Response_WriteLine("<p><form name=""frmMessage3PACT"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ onsubmit=""return Validate();"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Phase3"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" id=""idMessageType"" value=""PACT"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideLName"" value=""" & _clsMessageVAR.Gl_overrideLName & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideFName"" value=""" & _clsMessageVAR.Gl_overrideFName & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideL4"" value=""" & _clsMessageVAR.Gl_overrideL4 & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overridePhone"" value=""" & _clsMessageVAR.Gl_overridePhone & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideRCall"" value=""" & _clsMessageVAR.Gl_overrideRCall & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideReason"" value=""" & _clsMessageVAR.Gl_overrideReason & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideComment"" value=""" & _clsMessageVAR.Gl_overrideComment & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideDOB"" value=""" & _clsMessageVAR.Gl_overrideDOB & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideTeamColorize"" value=""" & _clsMessageVAR.Gl_overrideTeamColorize & """>")
                    Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" bordercolor=""#d6dbe9""><tr><td>")
                    Response_WriteLine("<table cellspacing=""0"">")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><font size=""5""><b>" & _clsMessageVAR.WebName & "</b></font></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center>Fill in Message Details and Submit</center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Site</td><td bgcolor=""#eeeeee"">&nbsp;" & Me.Whatsite & "&nbsp;" & Me.GetSiteName(Me.Whatsite) & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Location</td><td bgcolor=""#eeeeee"">&nbsp;" & Me.GetLocationName(Me.Whatlocation) & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    ' for new message takers, insert a Help message for certain criteria
                    bREMINDER = False

                    ' if hasn't submitted 100 messages yet, then show for this probationary period
                    MyCommand.CommandText = "SELECT COUNT(tab_Messages.Msg_Index) AS SUBMITCOUNT FROM tab_Messages WHERE tab_Messages.Msg_Username LIKE '" & Me.UserName & "';"

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            SUBMITCOUNT = -1
                        Else
                            sqlDataReader.Read()
                            ' total entries
                            SUBMITCOUNT = sqlDataReader.Item("SUBMITCOUNT")
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("SQL=" & MyCommand.CommandText & "<br>")
                    End If

                    If SUBMITCOUNT <= 100 Or SUBMITCOUNT Mod 100 = 0 Then
                        bREMINDER = True
                        FLAGCOUNT = "Not enough submits to check"
                    Else
                        ' this query takes between half and 1 second, skip the check if server overloaded in last 10 minutes
                        sec = Me.SecSinceOverload()
                        If sec >= 0 And sec < 600 Then
                            ' skip this now, server too busy
                            FLAGCOUNT = "Too busy to check"
                        Else
                            ' for those that have been flagged in the last 1 month
                            MyCommand.CommandText = "SELECT COUNT(tab_Messages.Msg_Index) AS FLAGCOUNT" & " FROM tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_UserName LIKE '" & Me.UserName & "'" & " AND tab_Audit.Au_Action = 'Flag'" & " AND tab_Audit.Au_Dt > "

                            If _clsMessageVAR.BUsesSqlString = True Then
                                MyCommand.CommandText = MyCommand.CommandText & "'" & DateAdd("m", -1, DateTime.Now.AddHours(dTimezoneOffset)) & "';"
                            Else
                                MyCommand.CommandText = MyCommand.CommandText & "'" & DateAdd("m", -1, DateTime.Now.AddHours(dTimezoneOffset)) & "#;"
                            End If

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    FLAGCOUNT = "Error counting flagged messages"
                                Else
                                    sqlDataReader.Read()
                                    ' total entries
                                    FLAGCOUNT = sqlDataReader.Item("FLAGCOUNT")
                                    If FLAGCOUNT > 0 Then
                                        bREMINDER = True
                                    End If
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("SQL=" & MyCommand.CommandText & "<br>")
                            End If

                        End If ' 0 <= sec < 600
                    End If

                    If bREMINDER = True Then
                        Response_WriteLine("<tr bgcolor=""#eeeeee""><td>&nbsp;</td><td><font color=""red""><b><u>Note</u></b><br>")
                        Response_WriteLine("Capturing accurate information helps teams more efficiently act on messages. Please ensure:<br>")
                        Response_WriteLine("- to select the appropriate team.<br>")
                        Response_WriteLine("- to provide the medication name on renewal requests.")
                        Response_WriteLine("</font>")
                        Response_WriteLine("</td></tr>")
                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    End If
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Team</td><td>" & Teamradio & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#d6dbe9"">&nbsp;Use either the Full ID or the Last/First/SSN fields.</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Full ID:&nbsp;</td><td>")
                    Response_WriteLine("<input type=""text"" name=""form_FullID"" id=""idFullID"" class=""form-control"" size=""50"" maxlength=""255"" autocomplete=""off"">")
                    Response_WriteLine("<div style=""position:static;background-color:white"">")
                    Response_WriteLine("<img align=""left"" alt=""FullID Hint"" name=""AppMod"" src=""images/AppMgmtMod.jpg"" width=""153"" height=""28"" onclick=""javascript:ShowBigImage();"" onmouseout=""javascript:ShowSmallImage();"">")
                    Response_WriteLine("<div id=""idFullIDHint"" style=""display:inline""> LAST,FIRST (XXXX)</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Last Name:&nbsp;</td><td><input type=""text"" name=""form_LastName"" id=""idLastName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient First Name:&nbsp;</td><td><input type=""text"" name=""form_FirstName"" id=""idFirstName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Last 4 SSN:&nbsp;</td><td><input type=""text"" name=""form_LastFour"" id=""idLastFour"" class=""form-control"" size=""5"" maxlength=""50"" autocomplete=""off""></td></tr>")
                    If _clsMessageVAR.Gl_overrideDOB = False Then
                        Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Date of Birth:&nbsp;</td><td><input type=""date"" name=""form_DOB"" id=""idDOB"" class=""form-control"" name=""birthday"" style=""width:30%;""></td></tr>")
                    Else
                        Response_WriteLine("<tr style=""display:none;""><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Date of Birth:&nbsp;</td><td><input type=""date"" name=""form_DOB"" id=""idDOB"" class=""form-control"" name=""birthday"" style=""display:none;""></td></tr>")
                    End If
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Patient Phone:&nbsp;</td><td>&nbsp;&nbsp;What is the best number we can use to contact you?<input type=""text"" name=""form_Phone"" id=""idPhone"" size=""14"" class=""form-control"" maxlength=""255"" autocomplete=""off""></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap>&nbsp;&nbsp;Return Call Expected:&nbsp;</td><td>" & ReturnRadio & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap></td><td><div id = ""idDivBestTime"" style=""display:none;"">&nbsp;&nbsp;Indicate how To find <i>Waiting</i> patient.</div></td>")
                    Response_WriteLine("<tr id=""idRowBestTime"" style=""display:none;"">")
                    Response_WriteLine("<td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap>Best Time to Callback:&nbsp;</td>")
                    Response_WriteLine("<td><input type=""text"" name=""form_BestTime"" id=""idBestTime"" class=""form-control"" size=""80"" maxlength=""255"" autocomplete=""off""></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td></td><td><div id=""idRedPharmMSGV23"" style=""display:none;""><font color=""red"">&nbsp;&nbsp;If counseling is needed, have patient talk to a pharmacist.</font></div></td></tr>")
                    Response_WriteLine("<tr><td></td><td><div id=""idRedPharmMSGOriginal"" style=""display:none;""><font color=""red"">&nbsp;&nbsp;If caller has refills remaining, connect to automated refill line.</font></div></td></tr>")
                    Response_WriteLine("<tr><td></td><td><div id=""idDivMedRefill"" style=""display:none;""></div></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"">Reason:&nbsp;</td><td>" & ReasonRadio)
                    Response_WriteLine("<tr><td></td><td><div id = ""idDivMedChoice"" style=""display:none;"">&nbsp;&nbsp;Do you want it mailed Or Do you want To pick it up?</div></td>")
                    Response_WriteLine("<tr id=""idRowMedChoice"" style=""display:none;"">")
                    Response_WriteLine("<td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Med Choice:&nbsp;</td>")
                    Response_WriteLine("<td><select name=""form_MedChoice"" id=""idMedChoice"" class=""form-control"">")
                    Response_WriteLine("<option selected></option>")
                    Response_WriteLine("<option value=""Mailed"">Mailed</option>")
                    Response_WriteLine("<option value=""Pickup"">Pickup</option>")
                    Response_WriteLine("<option value=""n/a"">n/a</option>")
                    Response_WriteLine("</select>")
                    Response_WriteLine("</td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr id=""idRowMedName"" style=""display:none;"">")
                    Response_WriteLine("<td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap>Medication Name:&nbsp;</td>")
                    Response_WriteLine("<td><input type=""text"" name=""form_MedName"" id=""idMedName"" class=""form-control"" size=""80"" maxlength=""255"" autocomplete=""off""></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Comment:&nbsp;</td><td><textarea name=""form_Comment"" id=""idComment"" class=""form-control"" rows=""12"" cols=""80""></textarea></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><input type=""submit"" name=""Submit"" class=""btn btn-primary"" id=""idSubmit"" value=""Submit""></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</td></tr></table>")
                    Response_WriteLine("</form>")
                    Response_WriteLine("</p></div></div>")
                    Response_WriteLine("<div><font color=""#eeeeee"">My Message Submits=" & SUBMITCOUNT & ", My Messages Flagged=" & FLAGCOUNT & ".</font></div>")
                    Response_WriteLine("			<script language=""javascript"">")
                    Response_WriteLine("				var BestTimeValue;")
                    Response_WriteLine("				var MedChoiceValue;")
                    Response_WriteLine("				var MedNameValue;")
                    Response_WriteLine("				BestTimeValue = """";")
                    Response_WriteLine("				MedChoiceValue = """";")
                    Response_WriteLine("				MedNameValue = """";")
                    Response_WriteLine("				// note that if person submits and hits BACK then the box can be checked but the BestTime won't be visible")
                    Response_WriteLine("				function ShowBestTime() {")
                    Response_WriteLine("					if (document.frmMessage3PACT.idBestTime.value != """") {")
                    Response_WriteLine("						// cache the BestTime textbox value in case it's turned off and later back on")
                    Response_WriteLine("						BestTimeValue = document.frmMessage3PACT.idBestTime.value;")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if ((document.frmMessage3PACT.idReturnCall.selectedIndex == 2) || (document.frmMessage3PACT.idReturnCall.selectedIndex == 3)) {")
                    Response_WriteLine("						// 0 = blank, 1 = No, 2 = Yes, 3 = Waiting")
                    Response_WriteLine("						// show the row for BestTime textbox")
                    Response_WriteLine("						idRowBestTime.style.display=""none"";")
                    Response_WriteLine("						// default the BestTime textbox to the previously chosen value")
                    Response_WriteLine("						document.frmMessage3PACT.idBestTime.value = BestTimeValue;")
                    Response_WriteLine("						if (document.frmMessage3PACT.idReturnCall.selectedIndex == 3) {")
                    Response_WriteLine("							// show the div for BestTime=Waiting explanation")
                    Response_WriteLine("							idDivBestTime.style.display=""none"";")
                    Response_WriteLine("						} else {")
                    Response_WriteLine("							// hide the div for BestTime=Waiting explanation")
                    Response_WriteLine("							idDivBestTime.style.display=""none"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// hide the row for BestTime textbox")
                    Response_WriteLine("						idRowBestTime.style.display=""none"";")
                    Response_WriteLine("						// hide the div for BestTime explanation")
                    Response_WriteLine("						idDivBestTime.style.display=""none"";")
                    Response_WriteLine("						// clear the BestTime textbox")
                    Response_WriteLine("						document.frmMessage3PACT.idBestTime.value = BestTimeValue;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				// HARD CODED values of 1, 2, 3 for medication!  The database table Reasons corresponds to these")
                    Response_WriteLine("				// if the Reasons table is ever adjusted this code may need to be tweaked.")
                    Response_WriteLine("				// note that if person submits and hits BACK then the box can be checked but the BestTime won't be visible")
                    Response_WriteLine("				function ShowMedChoice() {")
                    Response_WriteLine("					if (document.frmMessage3PACT.idMedChoice.selectedIndex != 0) {")
                    Response_WriteLine("						// 0 = blank, 1 = Mailed, 2 = Pickup, 3 = n/a")
                    Response_WriteLine("						// cache the MedChoice select index in case it's turned off and later back on")
                    Response_WriteLine("						MedChoiceValue = document.frmMessage3PACT.idMedChoice.selectedIndex;")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3PACT.idMedName.value != """") {")
                    Response_WriteLine("						// cache the MedName in case it's turned off and later back on")
                    Response_WriteLine("						MedNameValue = document.frmMessage3PACT.idMedName.value;")
                    Response_WriteLine("					}")
                    Response_WriteLine("					var e = document.getElementById(""idReason"");")
                    Response_WriteLine("					var value = e.options[e.selectedIndex].value;")
                    Response_WriteLine("					var Text = e.options[e.selectedIndex].text;")
                    Response_WriteLine("			        if ((Text.indexOf(""Medication"") >=0) || Text == ""VISN Pharmacy CCC – ASAP/Mail Today"" || Text == ""VISN Pharmacy CCC – Non Urgent"" || Text == ""VISN Pharmacy CCC – Window"") {")
                    Response_WriteLine("						if (Text != ""Medication (window pickup)"" && Text != ""Medication (expedited mail)"" && Text != ""Medication (local mail)"" && Text != ""Medication (CMOP mail)"") {")
                    Response_WriteLine("						    // 0 = blank, 1 = Medication Renewal, 2 = Medication Question, 3 = Medication Pain, 4 = Referral...")
                    Response_WriteLine("						    // show the row for MedChoice select and Med Name text")
                    Response_WriteLine("						    idRowMedChoice.style.display="""";")
                    Response_WriteLine("						    idRowMedName.style.display="""";")
                    Response_WriteLine("						    // default the MedChoice select box to the previously chosen value")
                    Response_WriteLine("						    document.frmMessage3PACT.idMedChoice.selectedIndex = MedChoiceValue;")
                    Response_WriteLine("						    // default the MedName value to the previously chosen value")
                    Response_WriteLine("						    document.frmMessage3PACT.idMedName.value = MedNameValue;")
                    Response_WriteLine("						    // show the div for MedChoice explanation")
                    Response_WriteLine("						    idRedPharmMSGV23.style.display=""none"";")
                    Response_WriteLine("                            if (Text != ""Community Care Rx/eRx (Medication)"" && Text != ""Expedited Shipping Request (Medication)"" && Text != ""Stock Check Rx (Medication)"" && Text != ""Supply Rx Renewal (Medication)"" && Text != ""ASAP (Medication)"" && Text != ""Non Urgent (Medication)"") {")
                    Response_WriteLine("						        idRedPharmMSGOriginal.style.display=""inline"";")
                    Response_WriteLine("                            }")
                    Response_WriteLine("						    idDivMedChoice.style.display=""inline"";")
                    Response_WriteLine("						    // show the div to better handle refills TODO: Refactor for V04")
                    Response_WriteLine("			                if (Text == ""Low/Out of Medication"" || Text == ""Medication recall"") {")
                    Response_WriteLine("						        idDivMedRefill.style.display=""none"";")
                    Response_WriteLine("						        idRedPharmMSGV23.style.display=""none"";")
                    Response_WriteLine("					        } else { idDivMedRefill.style.display=""inline""; }")
                    Response_WriteLine("					    } else { idRowMedChoice.style.display=""none""; idRowMedName.style.display=""""; idDivMedChoice.style.display=""none""; idDivMedRefill.style.display=""none""; idRedPharmMSGOriginal.style.display=""none""; idRedPharmMSGV23.style.display=""inline""; }")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// hide the row for MedChoice select and Med Name text")
                    Response_WriteLine("						idRowMedChoice.style.display=""none"";")
                    Response_WriteLine("						idRowMedName.style.display=""none"";")
                    Response_WriteLine("						// default the MedChoice select box to unselected")
                    Response_WriteLine("						document.frmMessage3PACT.idMedChoice.selectedIndex = 0;")
                    Response_WriteLine("						document.frmMessage3PACT.idMedName.value = """"")
                    Response_WriteLine("						// hide the div for MedChoice explanation")
                    Response_WriteLine("						idDivMedChoice.style.display=""none"";")
                    Response_WriteLine("						// shows the div to better handle refills")
                    Response_WriteLine("						idDivMedRefill.style.display=""none"";")
                    Response_WriteLine("						idRedPharmMSGOriginal.style.display=""none"";")
                    Response_WriteLine("						idRedPharmMSGV23.style.display=""none"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ShowBigImage() {")
                    Response_WriteLine("					//idAppModImage.innerHTML=""<img alt='FullID Hint' id='idImage' src='images/AppMgmtMod.jpg' width='611' height='118' onmouseout='javascript:ShowSmallImage();'>"";")
                    Response_WriteLine("					document.images.AppMod.width='611';")
                    Response_WriteLine("					document.images.AppMod.height='118';")
                    Response_WriteLine("					idFullIDHint.style.display=""none"";")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ShowSmallImage() {")
                    Response_WriteLine("					//idAppModImage.innerHTML=""<img alt='FullID Hint' id='idImage' src='images/AppMgmtMod.jpg' width='152' height='28'> onmouseover='javascript:ShowBigImage();'"";")
                    Response_WriteLine("					document.images.AppMod.width='152';")
                    Response_WriteLine("					document.images.AppMod.height='28';")
                    Response_WriteLine("					idFullIDHint.style.display=""inline"";")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function Validate() {")
                    Response_WriteLine("					var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;")
                    Response_WriteLine("					var errorfound;")
                    Response_WriteLine("					errorfound = ""Missing/Invalid:\r"";")
                    Response_WriteLine("					var oopsmessage;")
                    Response_WriteLine("					oopsmessage = """";")
                    Response_WriteLine("					var i;")
                    Response_WriteLine("					var Teamchecked;")
                    Response_WriteLine("					Teamchecked = false;")
                    Response_WriteLine("					var Teamcount;")
                    Response_WriteLine("					Teamcount = document.frmMessage3PACT.idTeam.length;")
                    Response_WriteLine("					if (isNaN(Teamcount)) {")
                    Response_WriteLine("						// single button")
                    Response_WriteLine("						if (document.frmMessage3PACT.idTeam.checked) {")
                    Response_WriteLine("							Teamchecked = true;")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// multiple buttons")
                    Response_WriteLine("						for (i=0;i<Teamcount;i++) {")
                    Response_WriteLine("							if (document.frmMessage3PACT.idTeam[i].checked) {")
                    Response_WriteLine("								Teamchecked = true;	")
                    Response_WriteLine("							}")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (!Teamchecked) {")
                    Response_WriteLine("						// no radio button is selected")
                    Response_WriteLine("						errorfound = errorfound + ""\rTeam"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3PACT.idFullID.value == """") {")
                    Response_WriteLine("						if (document.frmMessage3PACT.idLastName.value == """") {")
                    Response_WriteLine("                            if (document.frmMessage3PACT.form_overrideLName.value == ""False"") {")
                    Response_WriteLine("							    errorfound = errorfound + ""\rPatient Last Name"";")
                    Response_WriteLine("						    }")
                    Response_WriteLine("						}")
                    Response_WriteLine("						if (document.frmMessage3PACT.idFirstName.value == """") {")
                    Response_WriteLine("                            if (document.frmMessage3PACT.form_overrideFName.value == ""False"") {")
                    Response_WriteLine("							    errorfound = errorfound + ""\rPatient First Name"";")
                    Response_WriteLine("						    }")
                    Response_WriteLine("						}")
                    Response_WriteLine("						if (document.frmMessage3PACT.idLastFour.value == """") {")
                    Response_WriteLine("                            if (document.frmMessage3PACT.form_overrideL4.value == ""False"") {")
                    Response_WriteLine("							    errorfound = errorfound + ""\rPatient Last 4"";")
                    Response_WriteLine("						    }")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// can't submit both FullID and the individual name fields")
                    Response_WriteLine("						if (document.frmMessage3PACT.idLastName.value != """") {")
                    Response_WriteLine("							oopsmessage = ""Oops\r\rEither FullID OR Name and SSN fields\r\rNOT BOTH!"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("						if (document.frmMessage3PACT.idFirstName.value != """") {")
                    Response_WriteLine("							oopsmessage = ""Oops\r\rEither FullID OR Name and SSN fields\r\rNOT BOTH!"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("						if (document.frmMessage3PACT.idLastFour.value != """") {")
                    Response_WriteLine("							oopsmessage = ""Oops\r\rEither FullID OR Name and SSN fields\r\rNOT BOTH!"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("                    if (document.frmMessage3PACT.form_overrideDOB.value == ""False"") {")
                    Response_WriteLine("					    if (document.frmMessage3PACT.idDOB.value == """" || !document.frmMessage3PACT.idDOB.value.match(regex)) {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rPatient Date of Birth (mm/dd/yyyy)"";")
                    Response_WriteLine("					    }")
                    Response_WriteLine("					}")
                    Response_WriteLine("                    if (document.frmMessage3PACT.form_overrideDOB.value == ""True"") {")
                    Response_WriteLine("					    if (document.frmMessage3PACT.idDOB.value != """" && !document.frmMessage3PACT.idDOB.value.match(regex)) {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rPatient Date of Birth (mm/dd/yyyy)"";")
                    Response_WriteLine("					    }")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3PACT.idPhone.value == """") {")
                    Response_WriteLine("                        if (document.frmMessage3PACT.form_overridePhone.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rPatient Phone"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					// 0 = blank, 1 = No, 2 = Yes, 3 = Waiting")
                    Response_WriteLine("					if (document.frmMessage3PACT.idReturnCall.selectedIndex == 0) {")
                    Response_WriteLine("                        if (document.frmMessage3PACT.form_overrideRCall.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rReturn Call"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3PACT.idReason.selectedIndex == 0) {")
                    Response_WriteLine("                        if (document.frmMessage3PACT.form_overrideReason.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rReason"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("					var e = document.getElementById(""idReason"");")
                    Response_WriteLine("					var value = e.options[e.selectedIndex].value;")
                    Response_WriteLine("					var Text = e.options[e.selectedIndex].text;")
                    Response_WriteLine("						if ((Text.indexOf(""Medication"") >=0) || Text == ""VISN Pharmacy CCC – ASAP/Mail Today"" || Text == ""VISN Pharmacy CCC – Non Urgent"" || Text == ""VISN Pharmacy CCC – Window"") {")
                    Response_WriteLine("							// 0 = blank, 1 = Medication Renewal, 2 = Medication Question, 3 = Medication Pain, 4 = Referral...")
                    Response_WriteLine("							// then ensure MedChoice is selected.  ")
                    Response_WriteLine("							// else ignore MedChoice value")
                    Response_WriteLine("							if (Text != ""Medication (window pickup)"" && Text != ""Medication (expedited mail)"" && Text != ""Medication (local mail)"" && Text != ""Medication (CMOP mail)"") {")
                    Response_WriteLine("							    if (document.frmMessage3PACT.idMedChoice.value == 0) {")
                    Response_WriteLine("								    errorfound = errorfound + ""\rMed Choice"";")
                    Response_WriteLine("							    }  // MedChoice")
                    Response_WriteLine("							}")
                    Response_WriteLine("							if (document.frmMessage3PACT.idMedName.value == """") {")
                    Response_WriteLine("								errorfound = errorfound + ""\rMed Name"";")
                    Response_WriteLine("							}  // Med Name")
                    Response_WriteLine("						}  // MEDICATION reasons 1,2,3 and text VISN Pharmacy CCC* check for required MedChoice and MedName")
                    Response_WriteLine("					}  // reason OK")
                    Response_WriteLine("					if (document.frmMessage3PACT.idComment.value == """") {")
                    Response_WriteLine("                        if (document.frmMessage3PACT.form_overrideComment.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rComment"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (errorfound == ""Missing/Invalid:\r"") {")
                    Response_WriteLine("						if (oopsmessage == """") {")
                    Response_WriteLine("							// GOOD, STORE IT")
                    Response_WriteLine("							// prevents double clicking the submit button to submit it twice")
                    Response_WriteLine("							document.frmMessage3PACT.idSubmit.disabled = true;")
                    Response_WriteLine("							return true;")
                    Response_WriteLine("						} else {")
                    Response_WriteLine("							// BAD")
                    Response_WriteLine("							alert(oopsmessage + ""\rPlease correct and submit again."");")
                    Response_WriteLine("							return false;")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// BAD")
                    Response_WriteLine("						alert(oopsmessage + ""\r\r"" + errorfound + ""\rPlease correct and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("			</script>")
                Case "FEE"
                    ' Fee does not have ShowMedChoice field div show/hide functions

                    ReasonRadio = "<select name=""form_Reason"" id=""idReason"" class=""form-control"">" & vbCrLf & "<option value="""" selected></option>" & vbCrLf

                    sSqlString = "SELECT tab_Reasons.Re_Name FROM tab_Reasons WHERE tab_Reasons.Re_Type = 'FEE'" & " AND tab_Reasons.Re_Active = 'Yes' ORDER BY tab_Reasons.Re_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            ' uh oh, no active reasons                            
                        Else
                            While sqlDataReader.Read = True
                                ' replace " with encoded quote character 
                                ' single apostrophe ' = &#39;
                                ' quote " = &#34;
                                ' Replace(reasonrs("Re_Name"),"""","&#34;")
                                ' alternate method would need a DECODE after submit, before can use it:  Server.URLEncode(reasonrs("Re_Name"))
                                ReasonRadio = ReasonRadio & "<option value=""" & Replace(sqlDataReader.Item("Re_Name"), """", "&#34;") & """>" & sqlDataReader.Item("Re_Name") & "</option>" & vbCrLf
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ReasonRadio = ReasonRadio & "</select>" & vbCrLf

                    ' event=onchange:
                    '   annoying for using arrow keys to drop down to the selection as it jumps out at first arrow key.
                    '   best to do it with onblur as that's when the item loses focus.
                    ReturnRadio = "<select name=""form_ReturnCall"" id=""idReturnCall"" class=""form-control"" onblur=""javascript:ShowBestTime();"">" & "<option value="""" selected></option>" & "<option value=""No"">No</option>" & "<option value=""Yes"">Yes</option>" & "</select>"
                    Response_WriteLine("<p><form name=""frmMessage3FEE"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ onsubmit=""return Validate();"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Phase3"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" id=""idMessageType"" value=""FEE"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_FullID"" id=""idFullID"" value="""">")
                    Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" bordercolor=""#d6dbe9""><tr><td>")
                    Response_WriteLine("<table cellspacing=""0"">")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><font size=""5""><b>" & _clsMessageVAR.WebName & "</b></font></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center>Fill in Message Details and Submit</center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Site</td><td bgcolor=""#eeeeee"">&nbsp;" & Me.Whatsite & "&nbsp;" & Me.GetSiteName(Me.Whatsite) & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Location</td><td bgcolor=""#eeeeee"">&nbsp;" & Me.GetLocationName(Me.Whatlocation) & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Team</td><td>" & Teamradio & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Vendor Name</td><td><input type=""text"" name=""form_VendorName"" class=""form-control"" size=""30"" class=""form-control"" maxlength=""255"" autocomplete=""off""> [optional]</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Vendor Contact Info</td><td><input type=""text"" name=""form_VendorContactInfo"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""> [optional]</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Vendor Tax ID</td><td><input type=""text"" name=""form_VendorTaxID"" class=""form-control"" size=""30"" maxlength=""50"" autocomplete=""off""> [optional]</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#d6dbe9"">&nbsp;For vendor calls, multiple patients can be entered after submitting by cloning this message.</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Last Name</td><td><input type=""text"" name=""form_LastName"" id=""idLastName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient First Name</td><td><input type=""text"" name=""form_FirstName"" id=""idFirstName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Last 4 SSN</td><td><input type=""text"" name=""form_LastFour"" id=""idLastFour"" class=""form-control"" size=""5"" maxlength=""50"" autocomplete=""off""></td></tr>")
                    If _clsMessageVAR.Gl_overrideDOB = False Then
                        Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Date of Birth:&nbsp;</td><td><input type=""date"" name=""form_DOB"" id=""idDOB"" class=""form-control"" name=""birthday"" style=""width:30%;""></td></tr>")
                    Else
                        Response_WriteLine("<tr style=""display:none;""><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Date of Birth:&nbsp;</td><td><input type=""date"" name=""form_DOB"" id=""idDOB"" class=""form-control"" name=""birthday"" style=""display:none;""></td></tr>")
                    End If
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Phone</td><td><input type=""text"" name=""form_Phone"" id=""idPhone"" class=""form-control"" size=""14"" maxlength=""255"" autocomplete=""off""></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap>&nbsp;&nbsp;Return Call Expected</td><td>" & ReturnRadio & "</td></tr>")
                    Response_WriteLine("<tr id=""idRowBestTime"" style=""display:none;"">")
                    Response_WriteLine("<td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap>Best Time to Callback</td>")
                    Response_WriteLine("<td><input type=""text"" name=""form_BestTime"" id=""idBestTime"" class=""form-control"" size=""80"" maxlength=""255"" autocomplete=""off""></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"">Reason</td><td>" & ReasonRadio & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Comment</td><td><textarea name=""form_Comment"" id=""idComment"" class=""form-control"" rows=""12"" cols=""80""></textarea></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><input type=""submit"" name=""Submit"" class=""btn btn-primary"" id=""idSubmit"" value=""Submit""></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</td></tr></table>")
                    Response_WriteLine("</form>")
                    Response_WriteLine("</p>")
                    Response_WriteLine("			<script language=""javascript"">")
                    Response_WriteLine("				var BestTimeValue;")
                    Response_WriteLine("				BestTimeValue = """";")
                    Response_WriteLine("				// note that if person submits and hits BACK then the box can be checked but the BestTime won't be visible")
                    Response_WriteLine("				function ShowBestTime() {")
                    Response_WriteLine("					if (document.frmMessage3FEE.idBestTime.value != """") {")
                    Response_WriteLine("						// cache the BestTime textbox value in case it's turned off and later back on")
                    Response_WriteLine("						BestTimeValue = document.frmMessage3FEE.idBestTime.value;")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idReturnCall.selectedIndex == 2) {")
                    Response_WriteLine("						// 0 = blank, 1 = No, 2 = Yes")
                    Response_WriteLine("						// show the row for BestTime textbox")
                    Response_WriteLine("						idRowBestTime.style.display=""none"";")
                    Response_WriteLine("						// default the BestTime textbox to the previously chosen value")
                    Response_WriteLine("						document.frmMessage3FEE.idBestTime.value = BestTimeValue;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// hide the row for BestTime textbox")
                    Response_WriteLine("						idRowBestTime.style.display=""none"";")
                    Response_WriteLine("						// clear the BestTime textbox")
                    Response_WriteLine("						document.frmMessage3FEE.idBestTime.value = BestTimeValue;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ShowBigImage() {")
                    Response_WriteLine("					//idAppModImage.innerHTML=""<img alt='FullID Hint' id='idImage' src='images/AppMgmtMod.jpg' width='611' height='118' onmouseout='javascript:ShowSmallImage();'>"";")
                    Response_WriteLine("					document.images.AppMod.width='611';")
                    Response_WriteLine("					document.images.AppMod.height='118';")
                    Response_WriteLine("					idFullIDHint.style.display=""none"";")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ShowSmallImage() {")
                    Response_WriteLine("					//idAppModImage.innerHTML=""<img alt='FullID Hint' id='idImage' src='images/AppMgmtMod.jpg' width='152' height='28'> onmouseover='javascript:ShowBigImage();'"";")
                    Response_WriteLine("					document.images.AppMod.width='152';")
                    Response_WriteLine("					document.images.AppMod.height='28';")
                    Response_WriteLine("					idFullIDHint.style.display=""inline"";")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function Validate() {")
                    Response_WriteLine("					var errorfound;")
                    Response_WriteLine("					errorfound = ""Missing:\r"";")
                    Response_WriteLine("					var i;")
                    Response_WriteLine("					var Teamchecked;")
                    Response_WriteLine("					Teamchecked = false;")
                    Response_WriteLine("					var Teamcount;")
                    Response_WriteLine("					Teamcount = document.frmMessage3FEE.idTeam.length;")
                    Response_WriteLine("					if (isNaN(Teamcount)) {")
                    Response_WriteLine("						// single button")
                    Response_WriteLine("						if (document.frmMessage3FEE.idTeam.checked) {")
                    Response_WriteLine("							Teamchecked = true;")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// multiple buttons")
                    Response_WriteLine("						for (i=0;i<Teamcount;i++) {")
                    Response_WriteLine("							if (document.frmMessage3FEE.idTeam[i].checked) {")
                    Response_WriteLine("								Teamchecked = true;	")
                    Response_WriteLine("							}")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (!Teamchecked) {")
                    Response_WriteLine("						// no radio button is selected")
                    Response_WriteLine("						errorfound = errorfound + ""\rTeam"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idLastName.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient Last Name"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idFirstName.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient First Name"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idLastFour.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient Last 4"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idPhone.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient Phone"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					// 0 = blank, 1 = No, 2 = Yes")
                    Response_WriteLine("					if (document.frmMessage3FEE.idReturnCall.selectedIndex == 0) {")
                    Response_WriteLine("						errorfound = errorfound + ""\rReturn Call"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idReason.selectedIndex == 0) {")
                    Response_WriteLine("						errorfound = errorfound + ""\rReason"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessage3FEE.idComment.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rComment"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (errorfound == ""Missing:\r"") {")
                    Response_WriteLine("						// GOOD, STORE IT")
                    Response_WriteLine("						// prevents double clicking the submit button to submit it twice")
                    Response_WriteLine("						document.frmMessage3FEE.idSubmit.disabled = true;")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// BAD")
                    Response_WriteLine("						alert(errorfound + ""\r\rPlease correct and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("			</script>")
                Case Else
                    ' no other types available ... yet

            End Select

        Else
            Response_WriteLine("<p>")
            Response_WriteLine("<font color=red>Error - No Teams are active at this location</font><br>")
            Response_WriteLine("<br>")
            Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and try again.")
            Response_WriteLine("</p>")
        End If ' bFound = true
    End Sub

    Sub ShowMainMenuClone()
        Dim rsT, RType, CloneMsgTeamSelect, optionvalue, namelist, ReasonRadio, reasonrs
        Dim rsSiteNum, rsFullID, rsFirstName, rsLastName, rsLastFour, rsDateOfBirth, rsVendorName, rsVendorContactInfo, rsVendorTaxID, rsPhone
        Dim rsReturnCall, rsBestTime, rsMedChoice, rsMedName, rsReason, rsComment
        ' with the passing String values - question if passing a quote through a form will function

        ' these values are passed in from Process() for FEE:
        '<input type="hidden" name="form_submit" value="Yes">
        '<input type="hidden" name="form_Phase" value="Clone">
        '<input type="hidden" name="form_SiteNum" value="=whatsite"> ' 3 digit number code
        '<input type="hidden" name="form_LocationIndex" value="=whatlocation"> ' number
        '<input type="hidden" name="form_TeamIndex" value="=form_TeamIndex"> ' number
        '<input type="hidden" name="form_MessageType" value="=form_MessageType"> ' "FEE", "PACT"
        '<input type="hidden" name="form_MessageIndex" value="=nextindex"> ' number
        '<input type="submit" name="form_Submit" value="Clone Vendor Info to another Message">

        ' these values are passed in from message index viewing for PACT and FEE
        '<input type="hidden" name="form_submit" value="Yes">
        '<input type="hidden" name="form_Phase" value="Clone">
        '<input type="hidden" name="form_SiteNum" value="=rsSiteNum">
        '<input type="hidden" name="form_LocationIndex" value="=rsLocationIndex">
        '<input type="hidden" name="form_TeamIndex" value="=rsTeamIndex">
        '<input type="hidden" name="form_MessageType" value="=RType">
        '<input type="hidden" name="form_MessageIndex" value="=I">

        ' whatsite = Global from form_SiteNum
        ' whatlocation = Global from form_LocationIndex
        Dim form_TeamIndex, MessageType, MessageIndex, CloneType
        form_TeamIndex = Request.Form("form_TeamIndex")
        MessageType = Request.Form("form_MessageType")
        MessageIndex = Request.Form("form_MessageIndex")
        CloneType = Request.Form("form_CloneType")

        Dim sSqlString, rs, bFound


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        sSqlString = "SELECT * FROM tab_Messages WHERE tab_Messages.Msg_Index = " & MessageIndex & ";"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                bFound = False
            Else
                bFound = True

                rsSiteNum = sqlDataReader.Item("Msg_SiteNum")
                rsFullID = sqlDataReader.Item("Msg_FullID")
                rsFirstName = sqlDataReader.Item("Msg_FirstName")
                rsLastName = sqlDataReader.Item("Msg_LastName")
                rsLastFour = sqlDataReader.Item("Msg_LastFour")
                rsDateOfBirth = sqlDataReader.Item("Msg_DOB")
                rsVendorName = sqlDataReader.Item("Msg_VendorName")
                rsVendorContactInfo = sqlDataReader.Item("Msg_VendorContactInfo")
                rsVendorTaxID = sqlDataReader.Item("Msg_VendorTaxID")
                rsPhone = sqlDataReader.Item("Msg_Phone")
                rsReturnCall = sqlDataReader.Item("Msg_ReturnCall")
                rsBestTime = sqlDataReader.Item("Msg_BestTime")
                rsMedChoice = sqlDataReader.Item("Msg_MedChoice")
                rsMedName = sqlDataReader.Item("Msg_MedName")
                rsReason = sqlDataReader.Item("Msg_Reason")
                rsComment = sqlDataReader.Item("Msg_Comment")

                If IsDBNull(rsSiteNum) Then rsSiteNum = ""
                If IsDBNull(rsFullID) Then rsFullID = ""
                If IsDBNull(rsFirstName) Then rsFirstName = ""
                If IsDBNull(rsLastName) Then rsLastName = ""
                If IsDBNull(rsLastFour) Then rsLastFour = ""
                If IsDBNull(rsDateOfBirth) Then rsDateOfBirth = "" Else rsDateOfBirth = CDate(rsDateOfBirth).ToShortDateString()
                If IsDBNull(rsVendorName) Then rsVendorName = ""
                If IsDBNull(rsVendorContactInfo) Then rsVendorContactInfo = ""
                If IsDBNull(rsVendorTaxID) Then rsVendorTaxID = ""
                If IsDBNull(rsPhone) Then rsPhone = ""
                If IsDBNull(rsReturnCall) Then rsReturnCall = ""
                If IsDBNull(rsBestTime) Then rsBestTime = ""
                If IsDBNull(rsMedChoice) Then rsMedChoice = ""
                If IsDBNull(rsMedName) Then rsMedName = ""
                If IsDBNull(rsReason) Then rsReason = ""
                If IsDBNull(rsBestTime) Then rsBestTime = ""
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        If bFound = True Then
            Select Case MessageType

                Case "PACT"

                    ' although this is the "Clone" phase, the next phase is "Phase3" - to Process

                    RType = GetTypeFromTeamIndex(form_TeamIndex)

                    CloneMsgTeamSelect = "<select name=""form_CloneMsgTeam"" class=""form-control""><option selected></option>"

                    sSqlString = "SELECT tab_Teams.Te_Name, tab_Teams.Te_Index, tab_Locations.Lo_Name FROM tab_Teams LEFT JOIN tab_Locations" &
                    " ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" &
                    " WHERE tab_Locations.Lo_SiteNum = '" & rsSiteNum & "'"

                    If RType <> " " And RType <> "Missing" Then
                        ' if erroneously TeamIndex was NULL then RType wouldn't be valid so don't limit Team choices
                        sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                    End If

                    sSqlString = sSqlString & " AND tab_Teams.Te_Active = 'Yes' AND tab_Teams.Te_Index <> " & form_TeamIndex & " ORDER BY tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            ' uh oh, no active teams                            
                        Else
                            While sqlDataReader.Read
                                If sqlDataReader.Item("Te_Index") = form_TeamIndex Then
                                    ' skip
                                Else
                                    optionvalue = sqlDataReader.Item("Lo_Name") & " " & sqlDataReader.Item("Te_Name")
                                    namelist = GetTeamMemberNames(sqlDataReader.Item("Te_Index"), False, False)
                                    If namelist <> "" Then
                                        optionvalue = optionvalue & " - " & namelist
                                    End If
                                    If Len(optionvalue) > 99 Then
                                        optionvalue = Left(optionvalue, 99) & "..."
                                    End If
                                    CloneMsgTeamSelect = CloneMsgTeamSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & """>" & optionvalue & "</option>" & vbCrLf
                                End If
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    CloneMsgTeamSelect = CloneMsgTeamSelect & "</select>"

                    ReasonRadio = "<select name=""form_Reason"" id=""idReason"" class=""form-control"" onblur=""javascript:ShowMedChoice();"">" & vbCrLf
                    ReasonRadio = ReasonRadio & "<option value="""" selected></option>" & vbCrLf
                    sSqlString = "SELECT tab_Reasons.Re_Name FROM tab_Reasons WHERE tab_Reasons.Re_Type = '" & Replace(MessageType, "'", "''") & "'" & " AND tab_Reasons.Re_Active = 'Yes' ORDER BY tab_Reasons.Re_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            ' uh oh, no active reasons                            
                        Else
                            While sqlDataReader.Read = True
                                ' replace " with encoded quote character 
                                ' single apostrophe ' = &#39;
                                ' quote " = &#34;
                                ' Replace(reasonrs("Re_Name"),"""","&#34;")
                                ' alternate method would need a DECODE after submit, before can use it:  Server.URLEncode(reasonrs("Re_Name"))
                                ReasonRadio = ReasonRadio & "<option value=""" & Replace(sqlDataReader.Item("Re_Name"), """", "&#34;") & """>"
                                ReasonRadio = ReasonRadio & sqlDataReader.Item("Re_Name") & "</option>" & vbCrLf
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ReasonRadio = ReasonRadio & "</select>" & vbCrLf
                    Response_WriteLine("<p><div class=""container-fluid"">")
                    Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                    Response_WriteLine("<form name=""frmMessageCloneMainPACT"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ onsubmit=""return Validate();"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Phase3"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & MessageType & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_FullID"" value=""" & Replace(rsFullID, """", "&#34;") & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LastName"" value=""" & Replace(rsLastName, """", "&#34;") & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_FirstName"" value=""" & Replace(rsFirstName, """", "&#34;") & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LastFour"" value=""" & Replace(rsLastFour, """", "&#34;") & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_DOB"" value=""" & Replace(rsDateOfBirth, """", "&#34;") & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phone"" value=""" & Replace(rsPhone, """", "&#34;") & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideRCall"" value=""" & _clsMessageVAR.Gl_overrideRCall & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideReason"" value=""" & _clsMessageVAR.Gl_overrideReason & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideComment"" value=""" & _clsMessageVAR.Gl_overrideComment & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideDOB"" value=""" & _clsMessageVAR.Gl_overrideDOB & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_overrideTeamColorize"" value=""" & _clsMessageVAR.Gl_overrideTeamColorize & """>")
                    Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" bordercolor=""#d6dbe9""><tr><td><center>")
                    Response_WriteLine("<table cellspacing=""0"" cellspacing=""3"">")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><center><font size=""5""><b>" & _clsMessageVAR.WebName & "</b></font></center></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><center>Cloned Patient Info, Fill in New Message Details and Submit</center></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td>&nbsp;</td><td>&nbsp;Cloned message auto-loads these fields:</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"">Site</td><td>&nbsp;" & Me.Whatsite & "&nbsp;" & Me.GetSiteName(Me.Whatsite) & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"">Location</td><td>&nbsp;" & Me.GetLocationName(Me.Whatlocation) & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"">Team</td><td>&nbsp;" & Me.GetTeamName(form_TeamIndex) & "</td></tr>")
                    If rsFullID <> "" Then
                        Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Full ID</td><td>" & rsFullID & "</td></tr>")
                    End If
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Last Name</td><td>&nbsp;" & rsLastName & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient First Name</td><td>&nbsp;" & rsFirstName & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Last 4 SSN</td><td>&nbsp;" & rsLastFour & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Date of Birth</td><td>&nbsp;" & rsDateOfBirth & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Phone</td><td>&nbsp;" & rsPhone & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td>&nbsp;</td><td>&nbsp;Original message details shown for reference:</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Return Call</td><td>&nbsp;<i>" & rsReturnCall & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Best Time</td><td>&nbsp;<i>" & rsBestTime & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Reason</td><td>&nbsp;<i>" & rsReason & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Med Choice</td><td>&nbsp;<i>" & rsMedChoice & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Med Name</td><td>&nbsp;<i>" & rsMedName & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"" nowrap>Comment</td><td>&nbsp;<i>" & rsComment & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<!-- These fields do not use cached values: -->")
                    Response_WriteLine("<tr bgcolor=""#d6dbe9""><td>&nbsp;</td><td>&nbsp;Cloned message new fields -</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#d6dbe9""><td align=""right"" valign=""bottom"">Team:&nbsp;</td>")
                    Response_WriteLine("<td bgcolor=""#d6dbe9""><font color=""green""><small>&nbsp;&nbsp;Clone To <i>New</i> Team:</small></font><br>")
                    If CloneMsgTeamSelect = "<select name=""form_CloneMsgTeam"" class=""form-control""><option selected></option></select>" Then
                        Response_WriteLine("No other Teams at " & GetSiteName(rsSiteNum) & ".<br>")
                    Else
                        Response_WriteLine(CloneMsgTeamSelect)
                    End If
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>&nbsp;&nbsp;Return Call Expected:&nbsp;</td>")
                    Response_WriteLine("<td><select name=""form_ReturnCall"" id=""idReturnCall"" class=""form-control"" onblur=""javascript:ShowBestTime();"">")
                    Response_WriteLine("<option value="""" selected></option>")
                    Response_WriteLine("<option value=""No"">No</option>")
                    Response_WriteLine("<option value=""Yes"">Yes</option>")
                    Response_WriteLine("</select></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Best Time to Callback:&nbsp;</td>")
                    '  readOnly="readonly" style="background-color:silver"
                    Response_WriteLine("<td><div id=""idDivBestTime"" style=""display:none;"">&nbsp;&nbsp;Indicate how to find <i>Waiting</i> patient.</div><input type=""text"" name=""form_BestTime"" id=""idBestTime"" class=""form-control"" size=""80"" maxlength=""255"" autocomplete=""off"" value="""" disabled=""disabled"" style=""background-color:whitesmoke;""></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td></td><td><div id=""idRedPharmMSGV23"" style=""display:none;""><font color=""red"">&nbsp;&nbsp;If counseling is needed, have patient talk to a pharmacist.</font></div></td></tr>")
                    Response_WriteLine("<tr><td></td><td><div id=""idRedPharmMSGOriginal"" style=""display:none;""><font color=""red"">&nbsp;&nbsp;If caller has refills remaining, connect to automated refill line.</font></div></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"">Reason:&nbsp;</td><td><div id=""idDivMedRefill"" style=""display:none;""></div>" & ReasonRadio & "</td></tr>")
                    Response_WriteLine("<tr id=""idRowMedChoice"">")
                    Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Med Choice:&nbsp;</td>")
                    Response_WriteLine("<td><div id=""idDivMedChoice"" style=""display:none;"">&nbsp;&nbsp;Do you want it mailed or do you want to pick it up?</div><select name=""form_MedChoice"" id=""idMedChoice"" class=""form-control"" disabled=""disabled"">")
                    Response_WriteLine("<option selected></option>")
                    Response_WriteLine("<option value=""Mailed"">Mailed</option>")
                    Response_WriteLine("<option value=""Pickup"">Pickup</option>")
                    Response_WriteLine("<option value=""n/a"">n/a</option>")
                    Response_WriteLine("</select>")
                    Response_WriteLine("</td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr id=""idRowMedName"" style=""display:none;"">")
                    Response_WriteLine("<td bgcolor=""#dbe4f0"" align=""right"" valign=""top"" nowrap>Medication Name:&nbsp;</td>")
                    Response_WriteLine("<td><input type=""text"" name=""form_MedName"" id=""idMedName"" class=""form-control"" size=""80"" maxlength=""255"" autocomplete=""off""></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"">Comment:&nbsp;</td><td><textarea name=""form_Comment"" id=""idComment"" class=""form-control"" rows=""12"" cols=""80""></textarea></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><center><input type=""submit"" name=""Submit"" class=""btn btn-primary"" id=""idSubmit"" value=""Submit""></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</center></td></tr></table>")
                    Response_WriteLine("</form>")
                    Response_WriteLine("</div></div></p>")
                    Response_WriteLine("			<script language=""javascript"">")
                    Response_WriteLine("				var BestTimeValue;")
                    Response_WriteLine("				var MedChoiceValue;")
                    Response_WriteLine("				var MedNameValue;")
                    Response_WriteLine("				BestTimeValue = """";")
                    Response_WriteLine("				MedChoiceValue = """";")
                    Response_WriteLine("				MedNameValue = """";")
                    Response_WriteLine("				// note that if person submits and hits BACK then the box can be checked but the BestTime won't be visible")
                    Response_WriteLine("				function ShowBestTime() {")
                    Response_WriteLine("					if (document.frmMessageCloneMainPACT.idBestTime.disabled == false) {")
                    Response_WriteLine("						if (document.frmMessageCloneMainPACT.idBestTime.value != """") {")
                    Response_WriteLine("							// cache the BestTime textbox value in case it's turned off and later back on")
                    Response_WriteLine("							BestTimeValue = document.frmMessageCloneMainPACT.idBestTime.value;")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if ((document.frmMessageCloneMainPACT.idReturnCall.selectedIndex == 2) || (document.frmMessageCloneMainPACT.idReturnCall.selectedIndex == 3)) {")
                    Response_WriteLine("						// 0 = blank, 1 = No, 2 = Yes, 3 = Waiting")
                    Response_WriteLine("						// enable the BestTime textbox")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idBestTime.style.backgroundColor="""";")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idBestTime.disabled="""";")
                    Response_WriteLine("						// default the BestTime textbox to the previously chosen value")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idBestTime.value = BestTimeValue;")
                    Response_WriteLine("						if (document.frmMessageCloneMainPACT.idReturnCall.selectedIndex == 3) {")
                    Response_WriteLine("							// show the div for BestTime=Waiting explanation")
                    Response_WriteLine("							idDivBestTime.style.display=""none"";")
                    Response_WriteLine("						} else {")
                    Response_WriteLine("							// hide the div for BestTime=Waiting explanation")
                    Response_WriteLine("							idDivBestTime.style.display=""none"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// disable the BestTime textbox")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idBestTime.style.backgroundColor=""whitesmoke"";")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idBestTime.disabled=""disabled"";")
                    Response_WriteLine("						// clear the BestTime textbox")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idBestTime.value="""";")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				// HARD CODED values of 1, 2, 3 for medication!  The database table Reasons corresponds to these")
                    Response_WriteLine("				// if the Reasons table is ever adjusted this code may need to be tweaked.")
                    Response_WriteLine("				// note that if person submits and hits BACK then the box can be checked but the BestTime won't be visible")
                    Response_WriteLine("				function ShowMedChoice() {")
                    Response_WriteLine("					//if ((document.frmMessageCloneMainPACT.idMedChoice.selectedIndex == 1) || (document.frmMessageCloneMainPACT.idMedChoice.selectedIndex == 2) || (document.frmMessageCloneMainPACT.idMedChoice.selectedIndex == 3)) {")
                    Response_WriteLine("					if (document.frmMessageCloneMainPACT.idMedChoice.disabled == false) {")
                    Response_WriteLine("						if (document.frmMessageCloneMainPACT.idMedChoice.selectedIndex != 0) {")
                    Response_WriteLine("							// 0 = blank, 1 = Mailed, 2 = Pickup, 3 = n/a")
                    Response_WriteLine("							// cache the MedChoice select index in case it's turned off and later back on")
                    Response_WriteLine("							MedChoiceValue = document.frmMessageCloneMainPACT.idMedChoice.selectedIndex;")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainPACT.idMedName.value != """") {")
                    Response_WriteLine("						// cache the MedName in case it's turned off and later back on")
                    Response_WriteLine("						MedNameValue = document.frmMessageCloneMainPACT.idMedName.value;")
                    Response_WriteLine("					}")
                    Response_WriteLine("					var e = document.getElementById(""idReason"");")
                    Response_WriteLine("					var value = e.options[e.selectedIndex].value;")
                    Response_WriteLine("					var Text = e.options[e.selectedIndex].text;")
                    Response_WriteLine("					if ((Text.indexOf(""Medication"") >=0) || Text == ""VISN Pharmacy CCC – ASAP/Mail Today"" || Text == ""VISN Pharmacy CCC – Non Urgent"" || Text == ""VISN Pharmacy CCC – Window"") {")
                    Response_WriteLine("						// 0 = blank, 1 = Medication Renewal, 2 = Medication Question, 3 = Medication Pain, 4 = Referral...")
                    Response_WriteLine("						// enable the MedChoice select box")
                    Response_WriteLine("						if (Text != ""Medication (window pickup)"" && Text != ""Medication (expedited mail)"" && Text != ""Medication (local mail)"" && Text != ""Medication (CMOP mail)"") {")
                    Response_WriteLine("						    document.frmMessageCloneMainPACT.idMedChoice.style.backgroundColor="""";")
                    Response_WriteLine("						    document.frmMessageCloneMainPACT.idMedChoice.disabled="""";")
                    Response_WriteLine("						    // default the MedChoice select box to the previously chosen value")
                    Response_WriteLine("						    document.frmMessageCloneMainPACT.idMedChoice.selectedIndex = MedChoiceValue;")
                    Response_WriteLine("						    document.frmMessageCloneMainPACT.idMedName.value = MedNameValue;")
                    Response_WriteLine("						    // show the div for MedChoice explanation")
                    Response_WriteLine("						    idRedPharmMSGV23.style.display=""none"";")
                    Response_WriteLine("                            if (Text != ""Community Care Rx/eRx (Medication)"" && Text != ""Expedited Shipping Request (Medication)"" && Text != ""Stock Check Rx (Medication)"" && Text != ""Supply Rx Renewal (Medication)"" && Text != ""ASAP (Medication)"" && Text != ""Non Urgent (Medication)"") {")
                    Response_WriteLine("						        idRedPharmMSGOriginal.style.display=""inline"";")
                    Response_WriteLine("                            }")
                    Response_WriteLine("						    idDivMedChoice.style.display=""inline"";")
                    Response_WriteLine("						    idRowMedName.style.display="""";")
                    Response_WriteLine("						    // show the div to better handle refills")
                    Response_WriteLine("			                if (Text == ""Low/Out of Medication"" || Text == ""Medication recall"") {")
                    Response_WriteLine("						        idDivMedRefill.style.display=""none"";")
                    Response_WriteLine("					        } else { idDivMedRefill.style.display=""inline""; }")
                    Response_WriteLine("					    } else { idRowMedChoice.style.display=""none""; idRowMedName.style.display=""""; idDivMedChoice.style.display=""none""; idDivMedRefill.style.display=""none""; idRedPharmMSGOriginal.style.display=""none""; idRedPharmMSGV23.style.display=""inline""; }")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// disable the MedChoice select box")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idMedChoice.style.backgroundColor=""silver"";")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idMedChoice.disabled=""disabled"";")
                    Response_WriteLine("						// default the MedChoice select box to unselected")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idMedChoice.selectedIndex = 0;")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idMedName.value = """"")
                    Response_WriteLine(" 						// hide the div for MedChoice explanation")
                    Response_WriteLine("						idDivMedChoice.style.display=""none"";")
                    Response_WriteLine("						idRowMedName.style.display=""none"";")
                    Response_WriteLine("						// hide the div to better handle refills")
                    Response_WriteLine("						idDivMedRefill.style.display=""none"";")
                    Response_WriteLine("						idRedPharmMSGOriginal.style.display=""none"";")
                    Response_WriteLine("						idRedPharmMSGV23.style.display=""none"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function Validate() {")
                    Response_WriteLine("					var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;")
                    Response_WriteLine("					var errorfound;")
                    Response_WriteLine("					errorfound = ""Missing/Invalid:\r"";")
                    Response_WriteLine("    				if (document.frmMessageCloneMainPACT.idReturnCall.selectedIndex == 0) {")
                    Response_WriteLine("						// {0=blank}")
                    Response_WriteLine("                        if (document.frmMessageCloneMainPACT.form_overrideRCall.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rReturn Call"";")
                    Response_WriteLine("					    }")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainPACT.idReason.selectedIndex == 0) {")
                    Response_WriteLine("                        if (document.frmMessageCloneMainPACT.form_overrideReason.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rReason"";")
                    Response_WriteLine("					    }")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("					    var e = document.getElementById(""idReason"");")
                    Response_WriteLine("					    var value = e.options[e.selectedIndex].value;")
                    Response_WriteLine("					    var Text = e.options[e.selectedIndex].text;")
                    Response_WriteLine("						if ((Text.indexOf(""Medication"") >=0) || Text == ""VISN Pharmacy CCC – ASAP/Mail Today"" || Text == ""VISN Pharmacy CCC – Non Urgent"" || Text == ""VISN Pharmacy CCC – Window"") {")
                    Response_WriteLine("							// 0 = blank, 1 = Medication Renewal, 2 = Medication Question, 3 = Medication Pain, 4 = Referral...")
                    Response_WriteLine("							// then ensure MedChoice is selected.  ")
                    Response_WriteLine("							// else ignore MedChoice value")
                    Response_WriteLine("						    if (Text != ""Medication (window pickup)"" && Text != ""Medication (expedited mail)"" && Text != ""Medication (local mail)"" && Text != ""Medication (CMOP mail)"") {")
                    Response_WriteLine("							    if (document.frmMessageCloneMainPACT.idMedChoice.value == 0) {")
                    Response_WriteLine("								    errorfound = errorfound + ""\rMed Choice"";")
                    Response_WriteLine("							    }  // MedChoice")
                    Response_WriteLine("						    }")
                    Response_WriteLine("							if (document.frmMessageCloneMainPACT.idMedName.value == """") {")
                    Response_WriteLine("								errorfound = errorfound + ""\rMed Name"";")
                    Response_WriteLine("							}  // MedName")
                    Response_WriteLine("						}  // MEDICATION reasons 1,2,3 check for required MedChoice")
                    Response_WriteLine("					}  // reason OK")
                    Response_WriteLine("                    if (document.frmMessageCloneMainPACT.form_overrideDOB.value == ""False"") {")
                    Response_WriteLine("					    if (document.frmMessageCloneMainPACT.idDOB.value == """" || !document.frmMessageCloneMainPACT.idDOB.value.match(regex)) {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rDate of Birth (mm/dd/yyyy)"";")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("                    if (document.frmMessageCloneMainPACT.form_overrideDOB.value == ""True"") {")
                    Response_WriteLine("					    if (document.frmMessageCloneMainPACT.idDOB.value != """" && !document.frmMessageCloneMainPACT.idDOB.value.match(regex)) {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rPatient Date of Birth (mm/dd/yyyy)"";")
                    Response_WriteLine("					    }")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainPACT.idComment.value == """") {")
                    Response_WriteLine("                        if (document.frmMessageCloneMainPACT.form_overrideComment.value == ""False"") {")
                    Response_WriteLine("						    errorfound = errorfound + ""\rComment"";")
                    Response_WriteLine("					    }")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (errorfound == ""Missing/Invalid:\r"") {")
                    Response_WriteLine("						// GOOD, STORE IT")
                    Response_WriteLine("						// prevents double clicking the submit button to submit it twice")
                    Response_WriteLine("						document.frmMessageCloneMainPACT.idSubmit.disabled = true;")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// BAD")
                    Response_WriteLine("						alert(errorfound + ""\r\rPlease correct and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("			</script>")
                Case "FEE"
                    ' although this is the "Clone" phase the next phase is "Phase3" - to Process

                    RType = GetTypeFromTeamIndex(form_TeamIndex)

                    CloneMsgTeamSelect = "<select name=""form_CloneMsgTeam"" class=""form-control""><option selected></option>"

                    sSqlString = "SELECT tab_Teams.Te_Name, tab_Teams.Te_Index, tab_Locations.Lo_Name FROM tab_Teams LEFT JOIN tab_Locations" &
                    " ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" &
                    " WHERE tab_Locations.Lo_SiteNum = '" & rsSiteNum & "'"

                    If RType <> " " And RType <> "Missing" Then
                        ' if erroneously TeamIndex was NULL then RType wouldn't be valid so don't limit Team choices
                        sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                    End If

                    sSqlString = sSqlString & " AND tab_Teams.Te_Active = 'Yes' AND tab_Teams.Te_Index <> " & form_TeamIndex & " ORDER BY tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            ' uh oh, no active teams                            
                        Else
                            While sqlDataReader.Read
                                If sqlDataReader.Item("Te_Index") = form_TeamIndex Then
                                    ' skip
                                Else
                                    optionvalue = sqlDataReader.Item("Lo_Name") & " " & sqlDataReader.Item("Te_Name")
                                    namelist = GetTeamMemberNames(sqlDataReader.Item("Te_Index"), False, False)
                                    If namelist <> "" Then
                                        optionvalue = optionvalue & " - " & namelist
                                    End If
                                    If Len(optionvalue) > 99 Then
                                        optionvalue = Left(optionvalue, 99) & "..."
                                    End If
                                    CloneMsgTeamSelect = CloneMsgTeamSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & """>" & optionvalue & "</option>" & vbCrLf
                                End If
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    CloneMsgTeamSelect = CloneMsgTeamSelect & "</select>"

                    ReasonRadio = "<select name=""form_Reason"" id=""idReason"" class=""form-control"">" & vbCrLf
                    ReasonRadio = ReasonRadio & "<option value="""" selected></option>" & vbCrLf
                    sSqlString = "SELECT tab_Reasons.Re_Name FROM tab_Reasons WHERE tab_Reasons.Re_Type = '" & Replace(MessageType, "'", "''") & "'" & " AND tab_Reasons.Re_Active = 'Yes' ORDER BY tab_Reasons.Re_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            ' uh oh, no active reasons
                        Else
                            While sqlDataReader.Read = True
                                ' replace " with encoded quote character 
                                ' single apostrophe ' = &#39;
                                ' quote " = &#34;
                                ' Replace(reasonrs("Re_Name"),"""","&#34;")
                                ' alternate method would need a DECODE after submit, before can use it:  Server.URLEncode(reasonrs("Re_Name"))
                                ReasonRadio = ReasonRadio & "<option value=""" & Replace(sqlDataReader.Item("Re_Name"), """", "&#34;") & """>"
                                ReasonRadio = ReasonRadio & sqlDataReader.Item("Re_Name") & "</option>" & vbCrLf
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ReasonRadio = ReasonRadio & "</select>" & vbCrLf
                    Response_WriteLine("<p><form name=""frmMessageCloneMainFEE"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ onsubmit=""return Validate();"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Phase3"">")
                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & MessageType & """>")
                    Response_WriteLine("<input type=""hidden"" name=""form_FullID"" value="""">")
                    Select Case CloneType
                        Case "Vendor"
                            ' Vendor reason, include original vendor hidden form fields
                            Response_WriteLine("<input type=""hidden"" name=""form_VendorName"" id=""idVendorName"" value=""" & Replace(rsVendorName, """", "&#34;") & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_VendorContactInfo"" id=""idVendorContactInfo"" value=""" & Replace(rsVendorContactInfo, """", "&#34;") & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_VendorTaxID"" id=""idVendorTaxID"" value=""" & Replace(rsVendorTaxID, """", "&#34;") & """>")
                        Case "Patient"
                            ' Patient reason, include original patient hidden form fields
                            Response_WriteLine("<input type=""hidden"" name=""form_LastName"" id=""idLastName"" value=""" & Replace(rsLastName, """", "&#34;") & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_FirstName"" id=""idFirstName"" value=""" & Replace(rsFirstName, """", "&#34;") & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_LastFour"" id=""idLastFour"" value=""" & Replace(rsLastFour, """", "&#34;") & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_DOB"" id=""idDOB"" value=""" & Replace(rsDateOfBirth, """", "&#34;") & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_Phone"" id=""idPhone"" value=""" & Replace(rsPhone, """", "&#34;") & """>")
                        Case Else
                            ' oops, invalid clonetype for FEE
                    End Select
                    Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0"" bordercolor=""#d6dbe9""><tr><td><center>")
                    Response_WriteLine("<table cellspacing=""0"" cellspacing=""3"">")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><font size=""5""><b>" & _clsMessageVAR.WebName & "</b></font></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center>Cloned " & CloneType & " Info, Fill in New Message Details and Submit</center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Index</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;" & MessageIndex & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Site</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;" & Me.Whatsite & "&nbsp;" & Me.GetSiteName(Me.Whatsite) & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Location</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;" & Me.GetLocationName(Me.Whatlocation) & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" align=""right"" valign=""top"">Team</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;" & Me.GetTeamName(form_TeamIndex) & "</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Select Case CloneType
                        Case "Vendor"
                            ' Vendor reasons will show Patient fields as editable, thus include original Patient Fields for reference
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Vendor Name</td><td colspan=""2"">&nbsp;" & rsVendorName & "</td></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Vendor Contact Info</td><td colspan=""2"">&nbsp;" & rsVendorContactInfo & "</td></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Vendor Tax ID</td><td colspan=""2"">&nbsp;" & rsVendorTaxID & "</td></tr>")
                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><td>&nbsp;</td><td>&nbsp;Cloned message new fields:</td><td width=""100%"">&nbsp;Original message Patient info shown for reference:</td></tr>")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Last Name</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_LastName"" id=""idLastName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""></td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsLastName & "</i></td>")
                            Response_WriteLine("</tr>")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient First Name</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_FirstName"" id=""idFirstName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off""></td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsFirstName & "</i></td>")
                            Response_WriteLine("</tr>")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Last 4 SSN</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_LastFour"" id=""idLastFour"" class=""form-control"" size=""5"" maxlength=""50"" autocomplete=""off""></td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsLastFour & "</i></td>")
                            Response_WriteLine("</tr>")
                            If _clsMessageVAR.Gl_overrideDOB = False Then
                                Response_WriteLine("<tr>")
                                Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Date of Birth</td>")
                                Response_WriteLine("<td bgcolor=""white""><input type=""date"" name=""form_DOB"" id=""idDOB"" class=""form-control"" name=""birthday"" style=""width:30%;""></td>")
                                Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsDateOfBirth & "</i></td>")
                                Response_WriteLine("</tr>")
                            Else
                                Response_WriteLine("<tr style=""display:none;"">")
                                Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Date of Birth</td>")
                                Response_WriteLine("<td bgcolor=""white""><input type=""date"" name=""form_DOB"" id=""idDOB"" class=""form-control"" name=""birthday"" style=""width:30%;""></td>")
                                Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsDateOfBirth & "</i></td>")
                                Response_WriteLine("</tr>")
                            End If
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Patient Phone</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_Phone"" id=""idPhone"" class=""form-control"" size=""14"" maxlength=""255"" autocomplete=""off""></td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsPhone & "</i></td>")
                            Response_WriteLine("</tr>")
                        Case "Patient"
                            ' Patient reasons will show Vendor fields as editable, thus include original Vendor fields for reference
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Last Name</td><td colspan=""2"">&nbsp;" & rsLastName & "</td></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient First Name</td><td colspan=""2"">&nbsp;" & rsFirstName & "</td></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Last 4 SSN</td><td colspan=""2"">&nbsp;" & rsLastFour & "</td></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Date of Birth</td><td colspan=""2"">&nbsp;" & rsDateOfBirth & "</td></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Patient Phone</td><td colspan=""2"">&nbsp;" & rsPhone & "</td></tr>")
                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><td>&nbsp;</td><td>&nbsp;Cloned message new fields:</td><td width=""100%"">&nbsp;Original message Vendor info shown for reference:</td></tr>")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Vendor Name</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_VendorName"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off"">&nbsp;[optional]</td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsVendorName & "</i></td>")
                            Response_WriteLine("</tr>")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Vendor Contact Info</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_VendorContactInfo"" class=""form-control"" size=""30"" maxlength=""255"" autocomplete=""off"">&nbsp;[optional]</td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsVendorContactInfo & "</i></td>")
                            Response_WriteLine("</tr>")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Vendor Tax ID</td>")
                            Response_WriteLine("<td bgcolor=""white""><input type=""text"" name=""form_VendorTaxID"" class=""form-control"" size=""30"" maxlength=""50"" autocomplete=""off"">&nbsp;[optional]</td>")
                            Response_WriteLine("<td width=""100%"">&nbsp;<i>" & rsVendorTaxID & "</i></td>")
                            Response_WriteLine("</tr>")
                        Case Else
                            ' oops, invalid clonetype for FEE
                    End Select
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td>&nbsp;</td><td colspan=""2"">&nbsp;Original message details shown for reference:</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Return Call</td><td colspan=""2"">&nbsp;<i>" & rsReturnCall & "</i></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Best Time</td><td colspan=""2"">&nbsp;<i>" & rsBestTime & "</i></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Reason</td><td colspan=""2"">&nbsp;<i>" & rsReason & "</i></td></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right"" valign=""top"" nowrap>Comment</td><td colspan=""2"">&nbsp;<i>" & rsComment & "</i></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<!-- These fields do not use cached values: -->")
                    Response_WriteLine("<tr bgcolor=""#d6dbe9""><td>&nbsp;</td><td colspan=""2"">&nbsp;Cloned message new fields:</td></tr>")
                    Response_WriteLine("<tr bgcolor=""#d6dbe9""><td align=""right"" valign=""bottom"">Team</td>")
                    Response_WriteLine("<td bgcolor=""#d6dbe9""><font color=""green""><small>Clone To New Team:</small></font><br>")
                    If CloneMsgTeamSelect = "<select name=""form_CloneMsgTeam"" class=""form-control""><option selected></option></select>" Then
                        Response_WriteLine("No other Teams at " & GetSiteName(rsSiteNum) & ".<br>")
                    Else
                        Response_WriteLine(CloneMsgTeamSelect)
                    End If
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>&nbsp;&nbsp;Return Call Expected</td>")
                    Response_WriteLine("<td bgcolor=""white"" colspan=""2""><select name=""form_ReturnCall"" id=""idReturnCall"" class=""form-control"" onblur=""javascript:ShowBestTime();"">")
                    Response_WriteLine("<option value="""" selected></option>")
                    Response_WriteLine("<option value=""No"">No</option>")
                    Response_WriteLine("<option value=""Yes"">Yes</option>")
                    Response_WriteLine("</select></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"" nowrap>Best Time to Callback</td>")
                    '  readOnly="readonly" style="background-color:silver"
                    Response_WriteLine("<td bgcolor=""white"" colspan=""2""><input type=""text"" name=""form_BestTime"" id=""idBestTime"" class=""form-control"" size=""80"" maxlength=""255"" autocomplete=""off"" value="""" disabled=""disabled"" style=""background-color:whitesmoke;""></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"">Reason</td><td colspan=""2"">" & ReasonRadio & "</td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"" align=""right"" valign=""top"">Comment</td>")
                    Response_WriteLine("<td bgcolor=""white"" colspan=""2""><textarea name=""form_Comment"" id=""idComment"" class=""form-control"" rows=""12"" cols=""80""></textarea></td>")
                    Response_WriteLine("</tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""Submit"" class=""btn btn-primary"" id=""idSubmit"" value=""Submit""></center></td></tr>")
                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><font size=""1"">&nbsp;</font></td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</center></td></tr></table>")
                    Response_WriteLine("</form>")
                    Response_WriteLine("</p>")
                    Response_WriteLine("			<script language=""javascript"">")
                    Response_WriteLine("				var BestTimeValue;")
                    Response_WriteLine("				BestTimeValue = """";")
                    Response_WriteLine("				// note that if person submits and hits BACK then the box can be checked but the BestTime won't be visible")
                    Response_WriteLine("				function ShowBestTime() {")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idBestTime.disabled == false) {")
                    Response_WriteLine("						if (document.frmMessageCloneMainFEE.idBestTime.value != """") {")
                    Response_WriteLine("							// cache the BestTime textbox value in case it's turned off and later back on")
                    Response_WriteLine("							BestTimeValue = document.frmMessageCloneMainFEE.idBestTime.value;")
                    Response_WriteLine("						}")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idReturnCall.selectedIndex == 2) {")
                    Response_WriteLine("						// 0 = blank, 1 = No, 2 = Yes")
                    Response_WriteLine("						// enable the BestTime textbox")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idBestTime.style.backgroundColor="""";")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idBestTime.disabled="""";")
                    Response_WriteLine("						// default the BestTime textbox to the previously chosen value")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idBestTime.value = BestTimeValue;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// disable the BestTime textbox")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idBestTime.style.backgroundColor=""whitesmoke"";")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idBestTime.disabled=""disabled"";")
                    Response_WriteLine("						// clear the BestTime textbox")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idBestTime.value="""";")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function Validate() {")
                    Response_WriteLine("					var errorfound;")
                    Response_WriteLine("					errorfound = ""Missing:\r"";")
                    Response_WriteLine("					// FullID is blank during Clone for FEE")
                    Response_WriteLine("					// ReturnCall pre-filled but optional this time")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idLastName.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient Last Name"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idFirstName.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient First Name"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idLastFour.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPatient Last 4"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idPhone.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rPhone"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idReturnCall.selectedIndex == 0) {")
                    Response_WriteLine("						// {0=blank}")
                    Response_WriteLine("						errorfound = errorfound + ""\rReturn Call"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idReason.selectedIndex == 0) {")
                    Response_WriteLine("						errorfound = errorfound + ""\rReason"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (document.frmMessageCloneMainFEE.idComment.value == """") {")
                    Response_WriteLine("						errorfound = errorfound + ""\rComment"";")
                    Response_WriteLine("					}")
                    Response_WriteLine("					if (errorfound == ""Missing:\r"") {")
                    Response_WriteLine("						// GOOD, STORE IT")
                    Response_WriteLine("						// prevents double clicking the submit button to submit it twice")
                    Response_WriteLine("						document.frmMessageCloneMainFEE.idSubmit.disabled = true;")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						// BAD")
                    Response_WriteLine("						alert(errorfound + ""\r\rPlease correct and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("			</script>")
                Case Else
                    ' no other Clone types available ... yet
            End Select

        Else
            Response_WriteLine("<p><font color=""red"">ERROR - Message Index " & MessageIndex & " not found in database, unable to clone.</font></p>")
        End If ' bFound = true
    End Sub

    Sub Process()
        ' Get form values, store to database, send out email
        Dim sSqlStringSelect, sSqlStringInsert, sSqlStringValues, nextindex
        Dim mBestTime, mComment
        Dim bNotDupe, bSuccess, strInjectionFree, bCloneMsgNewTeam

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        bSuccess = False  ' default to false because the successful store will  it to true
        bNotDupe = True   ' default to true because hits will  it to false
        bCloneMsgNewTeam = False ' Added 2/14/2019 to compare against Original Message Team to ensure (new message) email goes to proper Team

        'form_SiteNum already loaded as a Global: whatsite
        'form_LocationIndex already loaded as Global: whatlocation
        Dim form_MessageType ' hidden pass-through = FEE or PACT
        Dim form_TeamIndex
        Dim form_CloneMsgTeam
        Dim form_FullID
        Dim form_LastName
        Dim form_FirstName
        Dim form_LastFour
        Dim form_DOB
        Dim temp_DOB
        Dim form_VendorName ' FEE type only, *optional*
        Dim form_VendorContactInfo ' FEE type only, *optional*
        Dim form_VendorTaxID ' FEE type only, *optional*
        Dim form_Phone
        Dim form_ReturnCall
        Dim form_BestTime
        Dim form_Reason
        Dim form_MedChoice ' PACT type only
        Dim form_MedName
        Dim form_Comment
        Dim form_overrideLName
        Dim form_overrideFName
        Dim form_overrideL4
        Dim form_overrideDOB
        Dim form_overridePhone
        Dim form_overrideRCall
        Dim form_overrideReason
        Dim form_overrideComment
        Dim errormessage

        form_MessageType = Request.Form("form_MessageType")
        form_TeamIndex = Request.Form("form_TeamIndex")
        form_CloneMsgTeam = Request.Form("form_CloneMsgTeam")
        form_FullID = Request.Form("form_FullID")
        form_LastName = Request.Form("form_LastName")
        form_FirstName = Request.Form("form_FirstName")
        form_LastFour = Request.Form("form_LastFour")
        form_DOB = Request.Form("form_DOB")
        form_VendorName = Request.Form("form_VendorName")
        form_VendorContactInfo = Request.Form("form_VendorContactInfo")
        form_VendorTaxID = Request.Form("form_VendorTaxID")
        form_Phone = Request.Form("form_Phone")
        form_ReturnCall = Request.Form("form_ReturnCall")
        form_BestTime = Request.Form("form_BestTime")
        form_Reason = Request.Form("form_Reason")
        form_MedChoice = Request.Form("form_MedChoice")
        form_MedName = Request.Form("form_MedName")
        'form_Comment = Request.Form("form_Comment") 'XSS bug discovered during sweep testing on 8/5 for chars < and >
        '... so encoded for ONLY < and > at this time... Nobody has reported such error in past when adding Comments.
        'Re-address to see if .aspx and web.config should be adjusted for requestValidationMode, or only allow A-Z input,etc.
        form_Comment = Request.Unvalidated("form_Comment")
        form_Comment = Replace(Replace(form_Comment, "<", "&lt;"), ">", "&gt;")
        form_overrideLName = Request.Form("form_overrideLName")
        form_overrideFName = Request.Form("form_overrideFName")
        form_overrideL4 = Request.Form("form_overrideL4")
        form_overrideDOB = Request.Form("form_overrideDOB")
        form_overridePhone = Request.Form("form_overridePhone")
        form_overrideRCall = Request.Form("form_overrideRCall")
        form_overrideReason = Request.Form("form_overrideReason")
        form_overrideComment = Request.Form("form_overrideComment")
        errormessage = ""

        ' test the text fields against sSqlString injection
        ' text fields for sSqlString injection testing: 
        '   form_FullID, form_LastName, form_FirstName, form_LastFour, form_DOB, form_Phone, form_BestTime, form_Comment
        strInjectionFree = ""

        ' Field Cleaning
        ' remove end white space, because the FullID field is loaded with overselection by the users...
        Do While Left(form_FullID, 1) = " "
            form_FullID = Right(form_FullID, Len(form_FullID) - 1)
        Loop
        Do While Right(form_FullID, 1) = " "
            form_FullID = Left(form_FullID, Len(form_FullID) - 1)
        Loop

        Do While Left(form_LastName, 1) = " "
            form_LastName = Right(form_LastName, Len(form_LastName) - 1)
        Loop
        Do While Right(form_LastName, 1) = " "
            form_LastName = Left(form_LastName, Len(form_LastName) - 1)
        Loop

        Do While Left(form_FirstName, 1) = " "
            form_FirstName = Right(form_FirstName, Len(form_FirstName) - 1)
        Loop
        Do While Right(form_FirstName, 1) = " "
            form_FirstName = Left(form_FirstName, Len(form_FirstName) - 1)
        Loop

        Do While Left(form_LastFour, 1) = " "
            form_LastFour = Right(form_LastFour, Len(form_LastFour) - 1)
        Loop
        Do While Right(form_LastFour, 1) = " "
            form_LastFour = Left(form_LastFour, Len(form_LastFour) - 1)
        Loop
        ' sometimes LastFour has parenthesis
        form_LastFour = Replace(form_LastFour, "(", "")
        form_LastFour = Replace(form_LastFour, ")", "")
        form_LastFour = Replace(form_LastFour, "-", "")

        ' "FEE" field cleaning
        Do While Left(form_VendorName, 1) = " "
            form_VendorName = Right(form_VendorName, Len(form_VendorName) - 1)
        Loop
        Do While Right(form_VendorName, 1) = " "
            form_VendorName = Left(form_VendorName, Len(form_VendorName) - 1)
        Loop
        Do While Left(form_VendorContactInfo, 1) = " "
            form_VendorContactInfo = Right(form_VendorContactInfo, Len(form_VendorContactInfo) - 1)
        Loop
        Do While Right(form_VendorContactInfo, 1) = " "
            form_VendorContactInfo = Left(form_VendorContactInfo, Len(form_VendorContactInfo) - 1)
        Loop
        Do While Left(form_VendorTaxID, 1) = " "
            form_VendorTaxID = Right(form_VendorTaxID, Len(form_VendorTaxID) - 1)
        Loop
        Do While Right(form_VendorTaxID, 1) = " "
            form_VendorTaxID = Left(form_VendorTaxID, Len(form_VendorTaxID) - 1)
        Loop

        ' global values that are filled in or emptied when calling sub ParseFullID(fullID).
        ' gLAST, gFIRST, gSSN
        Me.ParseFullID(form_FullID)

        ' Field Verification of form fields
        If Me.Whatsite = "" Then
            errormessage = errormessage & "Site field is Nothing.<br>"
        End If
        If Me.Whatlocation = "" Then
            errormessage = errormessage & "Location field is Nothing.<br>"
        End If
        If form_TeamIndex = "" Then
            errormessage = errormessage & "Team field is Nothing.<br>"
        End If
        If form_MessageType = "" Then
            errormessage = errormessage & "Message Type field is Nothing.<br>"
        End If

        Select Case form_MessageType
            Case "PACT"
                ' only check the Last, Full, SSN fields if FulLID is Nothing
                If form_FullID = "" Then
                    If form_LastName = "" And form_overrideLName = "False" Then
                        errormessage = errormessage & "Last Name field is Nothing.<br>"
                    Else
                        If Not Me.isValidsSqlString(form_LastName) Then
                            strInjectionFree = strInjectionFree & "<b>LastName:</b> " & form_LastName & "<br>" & vbCrLf
                        End If
                    End If
                    If form_FirstName = "" And form_overrideFName = "False" Then
                        errormessage = errormessage & "First Name field is Nothing.<br>"
                    Else
                        If Not Me.isValidsSqlString(form_FirstName) Then
                            strInjectionFree = strInjectionFree & "<b>FirstName:</b> " & form_FirstName & "<br>" & vbCrLf
                        End If
                    End If
                    If form_LastFour = "" And form_overrideL4 = "False" Then
                        errormessage = errormessage & "Last Four field is Nothing.<br>"
                    Else
                        If Not Me.isValidsSqlString(form_LastFour) Then
                            strInjectionFree = strInjectionFree & "<b>LastFour:</b> " & form_LastFour & "<br>" & vbCrLf
                        End If
                    End If
                    If form_DOB = "" And form_overrideDOB = "False" Then
                        errormessage = errormessage & "Date of Birth field is Nothing.<br>"
                    Else
                        If form_DOB <> "" And Not IsDate(form_DOB) Then
                            strInjectionFree = strInjectionFree & "<b>DOB format:</b> " & form_DOB & "<br>" & vbCrLf
                        End If
                    End If
                    If IsDate(form_DOB) Then temp_DOB = CDate(form_DOB).ToShortDateString()
                Else
                    ' FullID does have a value:
                    If Not Me.isValidsSqlString(form_FullID) Then
                        strInjectionFree = strInjectionFree & "<b>FullID:</b> " & form_FullID & "<br>" & vbCrLf
                    End If
                    ' ensure all 3 fields of FullID are used because too many people leave off Last4
                    If Me.GLAST = "" Then
                        errormessage = errormessage & "FullID is missing the Last Name portion.<br>"
                    Else
                        If Not Me.isValidsSqlString(Me.GLAST) Then
                            strInjectionFree = strInjectionFree & "<b>FullID's LastName:</b> " & Me.GLAST & "<br>" & vbCrLf
                        End If
                    End If
                    If Me.GFIRST = "" Then
                        errormessage = errormessage & "FullID is missing the First Name portion.<br>"
                    Else
                        If Not Me.isValidsSqlString(Me.GFIRST) Then
                            strInjectionFree = strInjectionFree & "<b>FullID's FirstName:</b> " & Me.GFIRST & "<br>" & vbCrLf
                        End If
                    End If
                    If Me.GSSN = "" Then
                        errormessage = errormessage & "FullID is missing the Last Four SSN portion.<br>"
                    Else
                        If Not Me.isValidsSqlString(Me.GSSN) Then
                            strInjectionFree = strInjectionFree & "<b>FullID's LastFour:</b> " & Me.GSSN & "<br>" & vbCrLf
                        End If
                    End If
                End If

            Case "FEE"
                If form_LastName = "" Then
                    errormessage = errormessage & "Last Name field is Nothing.<br>"
                Else
                    If Not Me.isValidsSqlString(form_LastName) Then
                        strInjectionFree = strInjectionFree & "<b>LastName:</b> " & form_LastName & "<br>" & vbCrLf
                    End If
                End If
                If form_FirstName = "" Then
                    errormessage = errormessage & "First Name field is Nothing.<br>"
                Else
                    If Not Me.isValidsSqlString(form_FirstName) Then
                        strInjectionFree = strInjectionFree & "<b>FirstName:</b> " & form_FirstName & "<br>" & vbCrLf
                    End If
                End If
                If form_LastFour = "" Then
                    errormessage = errormessage & "Last Four field is Nothing.<br>"
                Else
                    If Not Me.isValidsSqlString(form_LastFour) Then
                        strInjectionFree = strInjectionFree & "<b>LastFour:</b> " & form_LastFour & "<br>" & vbCrLf
                    End If
                End If
                If form_DOB = "" Then
                    errormessage = errormessage & "Date of Birth field is Nothing.<br>"
                Else
                    If form_DOB <> "" And Not IsDate(form_DOB) Then
                        strInjectionFree = strInjectionFree & "<b>DOB format:</b> " & form_DOB & "<br>" & vbCrLf
                    End If
                End If

                ' VendorName optional
                ' VendorContactInfo optional
                ' VendorTaxID optional
            Case Else
                ' hard code in some more type handlers for custom fields
        End Select

        If form_Phone = "" And form_overridePhone = "False" Then
            errormessage = errormessage & "Phone field is Nothing.<br>"
        Else
            If Not Me.isValidsSqlString(form_Phone) Then
                strInjectionFree = strInjectionFree & "<b>Phone:</b> " & form_Phone & "<br>" & vbCrLf
            End If
        End If
        If form_ReturnCall = "Yes" And form_overrideRCall = "False" Then
            If Not Me.isValidsSqlString(form_BestTime) Then
                strInjectionFree = strInjectionFree & "<b>BestTime:</b> " & form_BestTime & "<br>" & vbCrLf
            End If
        Else
            ' from new message:
            ' defaults to: form_ReturnCall = "No"
            ' from Cloned message:
            ' defaults to: form_ReturnCall = "n/a"
        End If
        If form_Reason = "" And form_overrideReason = "False" Then
            errormessage = errormessage & "Reason is Nothing.<br>"
        Else
            ' Reason is valid
            ' if MessageType is "PACT" then check for Medication reasons
            ' if Medication reasons, require MedChoice to have a value
            If form_MessageType = "PACT" Then
                If Left(form_Reason, 10) = "Medication" Then
                    If (InStr(form_Reason, "(window pickup)") + InStr(form_Reason, "(expedited mail)") + InStr(form_Reason, "(local mail)") + InStr(form_Reason, "(CMOP mail)")) = 0 Then
                        If form_MedChoice = "" Then
                            errormessage = errormessage & "Med Choice is Nothing.<br>"
                        End If
                        If form_MedName = "" Then
                            errormessage = errormessage & "Med Name is Nothing.<br>"
                        End If
                    Else
                        If form_MedName = "" Then
                            errormessage = errormessage & "Med Name is Nothing.<br>"
                        End If
                    End If
                End If
            Else
                ' FEE or other, MedChoice not required
            End If
        End If

        If form_Comment = "" And form_overrideComment = "False" Then
            errormessage = errormessage & "Comment field is Nothing.<br>"
        Else
            If Not Me.isValidsSqlString(form_Comment) Then
                strInjectionFree = strInjectionFree & "<b>Comment:</b> " & form_Comment & "<br>" & vbCrLf
            End If
        End If

        If errormessage <> "" Or strInjectionFree <> "" Then
            Response_WriteLine("<p>")
            Response_WriteLine("<font color=red><big><b>Error - Invalid Data</b></big></font><br>")
            Response_WriteLine("<br>")
            Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A>, correct the fields and submit again.<br>")
            Response_WriteLine("<br>")
            Response_WriteLine("<table border=""1"" cellspacing=""0"" bordercolor=""black"">")
            If strInjectionFree <> "" Then
                Response_WriteLine("<tr><td>" & strInjectionFree & "</td></tr>")
            End If
            If errormessage <> "" Then
                Response_WriteLine("<tr><td>" & errormessage & "</td></tr>")
            End If
            Response_WriteLine("</table>")
            Response_WriteLine("</p>")
        Else
            ' Insert into Database


            ' NOT INSERTED: Completed, Assigned, EmailSent, Status
            ' YES INSERTED: Index, SiteNum, LocationIndex, TeamIndex, 
            ' *FullID, *FirstName, *LastName, *LastFour, 
            ' Phone, ReturnCall, *BestTime, MedChoice, Reason, Comment
            ' Dt, Tm, Username, IP
            ' * = could be NULL or ""

            sSqlStringSelect = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_BestTime, tab_Messages.Msg_Comment FROM tab_Messages WHERE "
            sSqlStringInsert = "INSERT INTO tab_Messages ("

            ' Number Long Int
            ' sSqlStringSelect: check for duplicates in OPEN messages AND recently completed messages (within 7 days)
            ' This prevents duplicates when a user resubmits a cached form after the original message was completed
            sSqlStringSelect = sSqlStringSelect & "(tab_Messages.Msg_Completed IS NULL OR tab_Messages.Msg_Dt >= DATEADD(day, -7, GETDATE())) AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_Index, "
            sSqlStringValues = "zzz_nextindex, "

            ' Text 10
            ' form hidden from input button
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_SiteNum = '" & Me.Whatsite & "' AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_SiteNum, "
            sSqlStringValues = sSqlStringValues & "'" & Me.Whatsite & "', "

            ' Number Long Int
            ' form hidden from input button
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LocationIndex = " & Me.Whatlocation & " AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_LocationIndex, "
            sSqlStringValues = sSqlStringValues & Me.Whatlocation & ", "

            ' Number Long Int
            ' radio
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_TeamIndex = " & form_TeamIndex & " AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_TeamIndex, "
            If form_CloneMsgTeam <> "" Then
                bCloneMsgNewTeam = True
                sSqlStringValues = sSqlStringValues & form_CloneMsgTeam & ", "
            Else
                sSqlStringValues = sSqlStringValues & form_TeamIndex & ", "
            End If

            ' FullID section
            ' Text 255
            ' free text
            Select Case form_MessageType
                Case "PACT"
                    If form_FullID <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_FullID = '" & Replace(form_FullID, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_FullID, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_FullID, "'", "''") & "', "
                    End If

                    ' Text 255
                    ' free text
                    If form_FirstName <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_FirstName = '" & Replace(form_FirstName, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_FirstName, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_FirstName, "'", "''") & "', "
                    Else
                        ' form_FirstName is Nothing, use the parsed FullID for FirstName storage
                        If Me.GFIRST <> "" Then
                            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_FirstName = '" & Replace(Me.GFIRST, "'", "''") & "' AND "
                            sSqlStringInsert = sSqlStringInsert & "Msg_FirstName, "
                            sSqlStringValues = sSqlStringValues & "'" & Replace(Me.GFIRST, "'", "''") & "', "
                        End If
                    End If

                    ' Text 255
                    ' free text
                    If form_LastName <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LastName = '" & Replace(form_LastName, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_LastName, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_LastName, "'", "''") & "', "
                    Else
                        ' form_LastName is Nothing, use the parsed FullID for LastName storage
                        If Me.GLAST <> "" Then
                            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LastName = '" & Replace(Me.GLAST, "'", "''") & "' AND "
                            sSqlStringInsert = sSqlStringInsert & "Msg_LastName, "
                            sSqlStringValues = sSqlStringValues & "'" & Replace(Me.GLAST, "'", "''") & "', "
                        End If
                    End If

                    ' Text 50
                    ' free text
                    If form_LastFour <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LastFour = '" & Replace(form_LastFour, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_LastFour, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_LastFour, "'", "''") & "', "
                    Else
                        ' form_LastFour is Nothing, use the parsed FullID for LastFour
                        If Me.GSSN <> "" Then
                            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LastFour = '" & Replace(Me.GSSN, "'", "''") & "' AND "
                            sSqlStringInsert = sSqlStringInsert & "Msg_LastFour, "
                            sSqlStringValues = sSqlStringValues & "'" & Replace(Me.GSSN, "'", "''") & "', "
                        End If
                    End If

                    ' Date of Birth
                    If form_DOB <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_DOB = '" & Replace(form_DOB, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_DOB, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_DOB, "'", "''") & "', "
                    End If

                Case "FEE"

                    ' Text 255
                    ' free text
                    If form_FirstName <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_FirstName = '" & Replace(form_FirstName, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_FirstName, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_FirstName, "'", "''") & "', "
                    End If

                    ' Text 255
                    ' free text
                    If form_LastName <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LastName = '" & Replace(form_LastName, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_LastName, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_LastName, "'", "''") & "', "
                    End If

                    ' Text 50
                    ' free text
                    If form_LastFour <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_LastFour = '" & Replace(form_LastFour, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_LastFour, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_LastFour, "'", "''") & "', "
                    End If

                    ' Date of Birth
                    If form_DOB <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_DOB = '" & Replace(form_DOB, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_DOB, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_DOB, "'", "''") & "', "
                    End If

                    ' Text 255
                    ' free text
                    If form_VendorName <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_VendorName = '" & Replace(form_VendorName, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_VendorName, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_VendorName, "'", "''") & "', "
                    End If

                    ' Text 255
                    ' free text
                    If form_VendorContactInfo <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_VendorContactInfo = '" & Replace(form_VendorContactInfo, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_VendorContactInfo, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_VendorContactInfo, "'", "''") & "', "
                    End If

                    ' Text 50
                    ' free text
                    If form_VendorTaxID <> "" Then
                        sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_VendorTaxID = '" & Replace(form_VendorTaxID, "'", "''") & "' AND "
                        sSqlStringInsert = sSqlStringInsert & "Msg_VendorTaxID, "
                        sSqlStringValues = sSqlStringValues & "'" & Replace(form_VendorTaxID, "'", "''") & "', "
                    End If

                Case Else
                    ' hard coding here for other types

            End Select

            ' Text 255
            ' free text
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_Phone = '" & Replace(form_Phone, "'", "''") & "' AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_Phone, "
            sSqlStringValues = sSqlStringValues & "'" & Replace(form_Phone, "'", "''") & "', "

            ' Text 10
            ' select box {Yes, No}
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_ReturnCall = '" & form_ReturnCall & "' AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_ReturnCall, "
            sSqlStringValues = sSqlStringValues & "'" & form_ReturnCall & "', "

            ' Memo
            ' secondarily required - either free text or an Nothing field
            If form_BestTime <> "" Then
                ' MEMO, compare after: sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_BestTime = '" & Replace(form_BestTime, "'", "''") & "' AND "
                sSqlStringInsert = sSqlStringInsert & "Msg_BestTime, "
                sSqlStringValues = sSqlStringValues & "'" & Replace(form_BestTime, "'", "''") & "', "
            Else
                ' don't store the  Vb6.Null  value, not needed
            End If

            ' Text 10
            ' secondarily required - either Nothing string or select box of hard coded values {Mailed, Pickup, n/a}
            If form_MedChoice <> "" Then
                sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_MedChoice = '" & Replace(form_MedChoice, "'", "''") & "' AND "
                sSqlStringInsert = sSqlStringInsert & "Msg_MedChoice, "
                sSqlStringValues = sSqlStringValues & "'" & Replace(form_MedChoice, "'", "''") & "', "
            End If

            If form_MedName <> "" Then
                sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_MedName = '" & Replace(form_MedName, "'", "''") & "' AND "
                sSqlStringInsert = sSqlStringInsert & "Msg_MedName, "
                sSqlStringValues = sSqlStringValues & "'" & Replace(form_MedName, "'", "''") & "', "
            End If

            ' Text 255
            ' select box of database determined values
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_Reason = '" & Replace(form_Reason, "'", "''") & "' AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_Reason, "
            sSqlStringValues = sSqlStringValues & "'" & Replace(form_Reason, "'", "''") & "', "

            ' Memo
            ' free text
            ' MEMO, compare after: sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_Comment = '" & Replace(form_Comment, "'", "''") & "' AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_Comment, "
            sSqlStringValues = sSqlStringValues & "'" & Replace(form_Comment, "'", "''") & "', "

            ' skipping sSqlStringSelect: most likely date is the same, but new/"page refreshed" insert attempt could be next day or a couple days later
            ' Date Short Date
            sSqlStringInsert = sSqlStringInsert & "Msg_Dt, "
            ' #date# for access, 'date' for sSqlString
            If _clsMessageVAR.BUsesSqlString = True Then
                sSqlStringValues = sSqlStringValues & "'" & theDate & "', "
            Else
                sSqlStringValues = sSqlStringValues & "#" & theDate & "#, "
            End If

            ' skipping sSqlStringSelect: time is less if same day or anything if previous day(s)
            ' Date Long TIme
            sSqlStringInsert = sSqlStringInsert & "Msg_Tm, "
            ' #date# for access, 'date' for sSqlString
            If _clsMessageVAR.BUsesSqlString = True Then
                sSqlStringValues = sSqlStringValues & "'" & DateTime.Now.AddHours(dTimezoneOffset) & "', "
            Else
                sSqlStringValues = sSqlStringValues & "#" & DateTime.Now.AddHours(dTimezoneOffset) & "#, "
            End If

            ' Text 50
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_Username = '" & Replace(Me.UserName, "'", "''") & "' AND "
            sSqlStringInsert = sSqlStringInsert & "Msg_Username, "
            sSqlStringValues = sSqlStringValues & "'" & Replace(Me.UserName, "'", "''") & "', "

            ' Text 50
            ' Last value: no trailing comma
            sSqlStringSelect = sSqlStringSelect & "tab_Messages.Msg_IP = '" & Me.UserIP & "' "
            sSqlStringInsert = sSqlStringInsert & "Msg_IP"
            sSqlStringValues = sSqlStringValues & "'" & Me.UserIP & "'"

            sSqlStringSelect = sSqlStringSelect & " ORDER BY tab_Messages.Msg_Index DESC;"
            sSqlStringInsert = sSqlStringInsert & ") VALUES (" & sSqlStringValues & ");"

            If _clsMessageVAR.BDebug = True Then
                Response.Write("sSqlStringSelect=" & sSqlStringSelect & "<br>")
                Response.Write("sSqlStringInsert=" & sSqlStringInsert & "<br>")
            End If

            ' first check to ensure duplicate message doesn't already exist in OPEN messages
            ' Access limits memo fields to 255 in a WHERE clause, else errors
            ' sSqlString limits memo fields to 8000 in a WHERE clause, else errors
            ' ^^^ http://www.tek-tips.com/viewthread.cfm?qid=1461461

            MyCommand.CommandText = sSqlStringSelect

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    ' Good, duplicate message not found in OPEN messages, didn't even need to check MEMO fields
                    bNotDupe = True
                Else
                    While sqlDataReader.Read = True
                        mBestTime = sqlDataReader.Item("Msg_BestTime")
                        mComment = sqlDataReader.Item("Msg_Comment")
                        If IsDBNull(mBestTime) Then
                            mBestTime = ""
                        End If
                        If IsDBNull(mComment) Then
                            mComment = ""
                        End If

                        If mBestTime = form_BestTime And mComment = form_Comment Then
                            'if ( mBestTime=form_BestTime or (mBestTime="" and form_BestTime="") ) and ( mComment=form_Comment or (mComment="" and form_Comment="") ) then
                            'if StrComp(mBestTime,form_BestTime)=0 and strComp(mComment,form_Comment)=0 then
                            Response_WriteLine("<p><font color=""red"">This message is a duplicate with<br>")
                            Response_WriteLine("<a target=""_blank"" href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & Me.Whatsite & "&I=" & sqlDataReader.Item("Msg_Index") & """>" & sqlDataReader.Item("Msg_Index") & ". (Click to open in a new window)</a><br>")
                            Response_WriteLine("</font></p>")
                            bNotDupe = False
                        Else
                            ' this record isn't dupe, maybe others are, keep looping
                            ' don't  bNotDupe to true, don't want to overwrite previous hits in the loop
                        End If
                    End While
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

            If bNotDupe = True Then
                ' Write New Record into db

                MyCommand.CommandText = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM tab_Messages;"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Not sqlDataReader.HasRows Then
                        nextindex = 1
                    Else
                        sqlDataReader.Read()
                        If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                            nextindex = 1
                        Else
                            nextindex = sqlDataReader.Item("MAXINDEX") + 1
                        End If
                    End If
                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                ' don't replace sSqlStringInsert with a new string having the index hardcoded
                ' instead leave zzz_nextindex as a placeholder in case need to try again
                'On Error Resume Next
                sSqlStringInsert = Replace(sSqlStringInsert, "zzz_nextindex", nextindex)

                bSuccess = InsertTableRecord(sSqlStringInsert)

            Else
                ' Duplicate checking error messages
                Response_WriteLine("<p><font color=""red""><big>ERROR - Same message already exists in the database.</big><br>")
                Response_WriteLine("<br>")
                Response_WriteLine("It appears that Refresh was hit after already storing the message.<br>")
                Response_WriteLine("Click on <a href=""" & _clsMessageVAR.WebURL & """>New Message</a> to start over or <A HREF=""javascript:history.back()"">Back</A> and make adjustments.")
                Response_WriteLine("</font></p>")
                ' do NOT error handle the duplicate situation, it's a user refresh or BACK and submit common mistake.
            End If 'bNotDupe=true

            If bSuccess = True Then
                Response.Write("<p><font color=green>Message stored in database.</font><br>")

                ' Every 1000th Congratulations! Just for fun :)
                If nextindex Mod 1000 = 0 Then
                    Response_WriteLine("<p>")
                    Response_WriteLine("<table bordercolor=black border=1 bgcolor=#eeeeee cellspacing=0 cellpadding=10><tr><td>")
                    Response_WriteLine("<center>")
                    Response_WriteLine("&nbsp;<br>")
                    Response_WriteLine("&nbsp;<br>")
                    Response_WriteLine("<font color=red size=5>Congratulations!</font><br>")
                    Response_WriteLine("<br>")
                    Response_WriteLine("<font color=brown>You have completed the " & nextindex & "<small>th</small> Message!</font><br>")
                    Response_WriteLine("&nbsp;<br>")
                    Response_WriteLine("&nbsp;<br>")
                    Response_WriteLine("</center>")
                    Response_WriteLine("</td></tr></table>")
                    Response_WriteLine("</p>")
                End If

                Dim MSGemail, MSG, MSGto, MSGdelay

                ' MSGemail is the email message body and MSG is the display back to the web page
                If bCloneMsgNewTeam = True Then
                    MSGemail = "Message for " & Me.GetLocationName(Me.Whatlocation) & " - " & Me.GetTeamName(form_CloneMsgTeam) & "<br>" & vbCrLf & "Created: " & theDate & " @ " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>" & vbCrLf & "Reason: " & form_Reason & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & Me.Whatsite & "&I=" & nextindex & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & Me.Whatsite & "&I=" & nextindex & "</a>" & "<br>" & vbCrLf & "<br>" & vbCrLf & "To process the information, click the above link.  Login with your network account." & "<br>" & vbCrLf
                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                        MSG = "Location: " & Me.GetLocationName(Me.Whatlocation) & "<br>" & vbCrLf & "Team: " & Me.ColorizeTeamName(Me.GetTeamName(form_CloneMsgTeam)) & "<br>" & vbCrLf
                    Else
                        MSG = "Location: " & Me.GetLocationName(Me.Whatlocation) & "<br>" & vbCrLf & "Team: " & Me.ColorizeFont(Me.GetTeamName(form_CloneMsgTeam)) & "<br>" & vbCrLf
                    End If
                Else
                    MSGemail = "Message for " & Me.GetLocationName(Me.Whatlocation) & " - " & Me.GetTeamName(form_TeamIndex) & "<br>" & vbCrLf & "Created: " & theDate & " @ " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>" & vbCrLf & "Reason: " & form_Reason & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & Me.Whatsite & "&I=" & nextindex & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & Me.Whatsite & "&I=" & nextindex & "</a>" & "<br>" & vbCrLf & "<br>" & vbCrLf & "To process the information, click the above link.  Login with your network account." & "<br>" & vbCrLf
                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                        MSG = "Location: " & Me.GetLocationName(Me.Whatlocation) & "<br>" & vbCrLf & "Team: " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "<br>" & vbCrLf
                    Else
                        MSG = "Location: " & Me.GetLocationName(Me.Whatlocation) & "<br>" & vbCrLf & "Team: " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "<br>" & vbCrLf
                    End If
                End If

                Select Case form_MessageType
                    Case "PACT"
                        MSG = MSG & "Full ID: " & form_FullID & "<br>" & vbCrLf
                        If form_FullID <> "" Then
                            If Me.GLAST & "," & Me.GFIRST & " (" & Me.GSSN & ")" <> form_FullID Then
                                ' different from parsed value so show it
                                MSG = MSG & "<font color=""gray"">Full ID: " & Me.GLAST & ", " & Me.GFIRST & " (" & Me.GSSN & ")</font><br>"
                            End If
                        End If
                        MSG = MSG & "Last Name: " & form_LastName & "<br>" & vbCrLf & "First Name: " & form_FirstName & "<br>" & vbCrLf & "Last Four: " & form_LastFour & "<br>" & vbCrLf & "Date of Birth: " & temp_DOB & "<br>" & vbCrLf
                    Case "FEE"
                        ' no FullID for FEE
                        MSG = MSG & "Last Name: " & form_LastName & "<br>" & vbCrLf & "First Name: " & form_FirstName & "<br>" & vbCrLf & "Last Four: " & form_LastFour & "<br>" & vbCrLf & "Date of Birth: " & temp_DOB & "<br>" & vbCrLf & "Vendor Name: " & form_VendorName & "<br>" & vbCrLf & "Vendor Contact Info: " & form_VendorContactInfo & "<br>" & vbCrLf & "Vendor Tax ID: " & form_VendorTaxID & "<br>" & vbCrLf
                    Case Else
                        ' hard code future items here
                End Select
                MSG = MSG & "Phone: " & form_Phone & "<br>" & vbCrLf & "Return Call Expected: " & form_ReturnCall & "<br>" & vbCrLf & "Best Time to Callback: " & form_BestTime & "<br>" & vbCrLf & "Reason: " & form_Reason & "<br>" & vbCrLf
                If form_MessageType = "PACT" Then
                    MSG = MSG & "Med Choice: " & form_MedChoice & "<br>" & vbCrLf
                    MSG = MSG & "Med Name: " & form_MedName & "<br>" & vbCrLf
                End If
                MSG = MSG & "Comment: " & Replace(form_Comment, vbCrLf, "<br>") & "<br>" & vbCrLf & "Submit Date: " & theDate & "<br>" & vbCrLf & "Submit Time: " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>" & vbCrLf
                If Me.UserName <> "None" Then
                    MSG = MSG & "Submit UserName: " & UserName & "<br>" & vbCrLf
                End If
                ' don't show the IP to the user...
                'MSG = MSG & "Submit User IP: " & UserIP & "<br>" & VbCrLf


                If MSGemail <> "" Then
                    ' send the email
                    ' uses MSGemail

                    ' Success = "Yes"
                    ' Skipped = "Skipped"
                    ' initial fail = "Error"
                    ' 2nd attempt fail = "TriedAgain"
                    ' 3rd attempt fail = "Failed"

                    If bCloneMsgNewTeam = True Then
                        MSGto = Me.GetTeamMemberNewEmails(form_CloneMsgTeam)
                    Else
                        MSGto = Me.GetTeamMemberNewEmails(form_TeamIndex)
                    End If
                    If MSGto = "" Then
                        ' No emails listed for the chosen Team
                        Response.Write("<p><font color=navy>Team has <i>New Message Emails</i> turned off so skipping email.</font></p>")

                        UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'Skipped' WHERE tab_Messages.Msg_Index = " & nextindex & ";")

                    Else
                        ' send the email	
                        If Me.SendTheMessage(MSGto, MSGemail) = True Then
                            ' success
                            Response.Write("<p><font color=green>E-mail sent to " & MSGto & ".</font></p>")
                            ' store the "Yes" to the database
                            UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'Yes' WHERE tab_Messages.Msg_Index = " & nextindex & ";")

                            ' since email was successfully proven, attempt to resend (now that the mail servers are reachable!?!)
                            ' attempt to re-send previous failures
                            ' only attempt when succesful, not when server is failing
                            Dim MSGretry

                            MyCommand.CommandText = "SELECT * FROM tab_Messages" & " WHERE (tab_Messages.Msg_EmailSent = 'Error' OR tab_Messages.Msg_EmailSent = 'TriedAgain' OR tab_Messages.Msg_EmailSent IS NULL)" & " AND tab_Messages.Msg_Index <> " & nextindex & " AND tab_Messages.Msg_Completed IS NULL" & " AND tab_Messages.Msg_Assigned IS NULL" & " ORDER BY tab_Messages.Msg_Index DESC;"

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                While sqlDataReader.Read = True
                                    Response_WriteLine("<p><table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>Attempting Email re-send for previously failed email attempts:<br><br>")
                                    MSGretry = "Message for " & Me.GetLocationName(sqlDataReader.Item("Msg_LocationIndex")) & " - " & Me.GetTeamName(sqlDataReader.Item("Msg_TeamIndex")) & "<br>" & vbCrLf & "Created: " & sqlDataReader.Item("Msg_Dt") & " @ " & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & sqlDataReader.Item("Msg_SiteNum") & "&I=" & sqlDataReader.Item("Msg_Index") & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & sqlDataReader.Item("Msg_SiteNum") & "&I=" & sqlDataReader.Item("Msg_Index") & "</a>" & "<br>" & vbCrLf & "<br>" & vbCrLf & "To process the information, click the above link.  Login with your network account." & "<br>" & vbCrLf & "(this message is a re-send of a previous attempt)" & "<br>" & vbCrLf

                                    ' load recipient list from Message's TeamIndex
                                    MSGto = Me.GetTeamMemberNewEmails(sqlDataReader.Item("Msg_TeamIndex"))

                                    ' MSGto should have a value as previous sends tried, but someone could toggle Members off in the meantime
                                    If MSGto = "" Then
                                        ' set it to Skipped
                                        Response_WriteLine("<font color=""orange"">E-mail resend attempt for index " & sqlDataReader.Item("Msg_Index") & " no longer has email recipients available. Will not try again.</font><br>")

                                        UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'Skipped' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")

                                    Else
                                        If Me.SendTheMessage(MSGto, MSGretry) = True Then
                                            ' good resend
                                            ' store the "Yes" to the database
                                            Response_WriteLine("<font color=""orange"">E-mail resend attempt for index " & sqlDataReader.Item("Msg_Index") & " sent successfully.</font><br>")

                                            UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'Yes' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")

                                        Else
                                            ' bad
                                            ' store as "TriedAgain" or "Failed"
                                            If sqlDataReader.Item("Msg_EmailSent") = "Error" Or IsDBNull(sqlDataReader.Item("Msg_EmailSent")) Then
                                                ' store as "TriedAgain"
                                                Response_WriteLine("<font color=""orange"">E-mail resend attempt for index " & sqlDataReader.Item("Msg_Index") & " failed. Will try 1 more time.</font><br>")

                                                UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'TriedAgain' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")

                                            Else
                                                ' tried twice, give up, store as "Failed"
                                                Response_WriteLine("<font color=""orange"">E-mail resend attempt for index " & sqlDataReader.Item("Msg_Index") & " failed. Will not try again.</font><br>")

                                                UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'Failed' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")

                                            End If
                                        End If
                                    End If
                                End While
                                Response_WriteLine("</td></tr></table></p>")

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                        Else

                            ' failure
                            Response_WriteLine("<p>")
                            Response_WriteLine("<font color=red>ERROR: Email server did not respond.<br>")
                            Response_WriteLine("Could not send email to " & MSGto & ".</font><br>")
                            Response_WriteLine("<font color=green>Don't worry though, the message did store to the database.<br>")
                            Response_WriteLine("Email send will retry when the mail server responds again.</font>")
                            Response_WriteLine("</p>")

                            ' store the fail to the database
                            UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_EmailSent = 'Error' WHERE tab_Messages.Msg_Index = " & nextindex & ";")

                        End If ' SendTheMessage = true
                    End If ' MSGto = ""
                End If ' MSGemail <> ""

                ' format the displays
                Response_WriteLine("<p><table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td><table>")
                ' provide average completion time in hours for this team for this reason
                ' function ShowAverage(ti, reason)
                ' returns "" if server was too busy in last 30 minutes to run this query
                MSGdelay = Me.ShowAverage(form_TeamIndex, form_Reason)
                If MSGdelay <> "" Then
                    Response_WriteLine("<tr valign=""top"">")
                    Response_WriteLine("<td bgcolor=""#dbe4f0""><b>Average Delays</b></td>")
                    Response_WriteLine("<td>" & MSGdelay & "</td>")
                    Response_WriteLine("</tr>")
                End If

                ' provide Scripts to read to the caller
                ' ShowScript(reason Text Field, LocationIndex Number field)
                Response_WriteLine("<tr valign=""top"">")
                Response_WriteLine("<td bgcolor=""#dbe4f0""><b>Read Back Scripts</b></td>")
                Response_WriteLine("<td>" & Me.ShowScript(form_Reason, Me.Whatlocation) & "")
                Response_WriteLine("</td>")
                Response_WriteLine("</tr>")
                ' Offer Clone message type

                Select Case form_MessageType
                    Case "FEE"
                        If InStr(form_Reason, "Vendor") Then
                            Response_WriteLine("<tr><td valign=""top"" bgcolor=""#d6dbe9""><b>Clone Vendor?</b></td>")
                            Response_WriteLine("<td bgcolor=""#eeeeee"">Third party callers (insurance companies, other medical billing departments)<br>")
                            Response_WriteLine("may inquire about multiple veterans during the same call.<br>")
                            Response_WriteLine("<br>")
                            Response_WriteLine("Clone the caller info into another message to create entries for each veteran.<br>")
                            Response_WriteLine("<br>")
                            Response_WriteLine("<form name=""frmMessageCloneFromProcessFEEVendor"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:4;margin-bottom:4"">")
                            Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                            Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Clone"">")
                            Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & form_MessageType & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_MessageIndex"" value=""" & nextindex & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_CloneType"" value=""Vendor"">")
                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Clone Vendor Info to another Message"">")
                            Response_WriteLine("</form>")
                            Response_WriteLine("</td>")
                            Response_WriteLine("</tr>")
                        Else
                            Response_WriteLine("<tr><td valign=""top"" bgcolor=""#d6dbe9""><b>Clone Patient?</b></td>")
                            Response_WriteLine("<td bgcolor=""#eeeeee"">Sometimes a patient calls about multiple topics.<br>")
                            Response_WriteLine("Submit as separate messages as each topic is routed independently to appropriate staff for resolution.<br>")
                            Response_WriteLine("<br>")
                            Response_WriteLine("<form name=""frmMessageCloneFromProcessFEEPatient"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:4;margin-bottom:4"">")
                            Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                            Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Clone"">")
                            Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & form_MessageType & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_MessageIndex"" value=""" & nextindex & """>")
                            Response_WriteLine("<input type=""hidden"" name=""form_CloneType"" value=""Patient"">")
                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Clone Patient Info to another Message"">")
                            Response_WriteLine("</form>")
                            Response_WriteLine("</td>")
                            Response_WriteLine("</tr>")
                        End If
                    Case "PACT"
                        ' sometimes a patient has more than 1 need.  Submit it as multiple messages
                        Response_WriteLine("<tr><td valign=""top"" bgcolor=""#d6dbe9""><b>Clone Patient?</b></td>")
                        Response_WriteLine("<td bgcolor=""#eeeeee"">Sometimes a patient calls about multiple topics.<br>")
                        Response_WriteLine("Submit as separate messages as each topic is routed independently to appropriate staff for resolution.<br>")
                        Response_WriteLine("<br>")
                        Response_WriteLine("<form name=""frmMessageCloneFromProcessPACT"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:4;margin-bottom:4"">")
                        Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                        Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Clone"">")
                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & Me.Whatsite & """>")
                        Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.Whatlocation & """>")
                        Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                        Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & form_MessageType & """>")
                        Response_WriteLine("<input type=""hidden"" name=""form_MessageIndex"" value=""" & nextindex & """>")
                        Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Clone Patient Info to another Message"">")
                        Response_WriteLine("</form>")
                        Response_WriteLine("</td>")
                        Response_WriteLine("</tr>")
                    Case Else

                End Select

                ' write back to the screen so the user can see all that was entered.
                Response_WriteLine("<tr><td valign=""top"" bgcolor=""#d6dbe9""><b>Email Message Body</b></td>")
                Response_WriteLine("<td>" & MSGemail & "</td>")
                Response_WriteLine("</tr>")
                ' write back to the screen so the user can see all that was entered.
                Response_WriteLine("<tr><td valign=""top"" bgcolor=""#d6dbe9""><b>Message Details</b></td>")
                Response_WriteLine("<td>" & MSG & "</td>")
                Response_WriteLine("</tr>")
                Response_WriteLine("</table></td></tr></table></p>")
            Else
                ' bSuccess=false error messages have already been displayed.
            End If ' bSuccess = true

        End If ' errormessage <> ""
    End Sub
    Sub ShowAdminMenu()
        Err.Clear() ' Garrett and John reported that errors are encountered here when they first used new url. Let's clear the error object and see what happens for subsequent users.
        ' Admin Menu Choices
        Dim sAge As String
        Dim sSqlString, LongI, action, menu, isSingleSite, sort, countOpen, navBar, colSpan, sec

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        ' Globals used:
        ' S = Site
        ' I = Index

        '****
        ' used to populate S, SiteName, and whatsite
        If S = "" Then
            isSingleSite = Me.SingleSite()
        End If
        '****

        If (Not Request.QueryString("menu") Is Nothing) Then
            menu = Request.QueryString("menu").ToString()
        Else
            menu = ""
        End If

        If (Not Request.QueryString("action") Is Nothing) Then
            action = Request.QueryString("action").ToString()
        Else
            action = ""
        End If

        If action = "" Then
            ' members get "My Assigned" and "My Team"
            If Me.AdminAccess = "Member" Then
                action = "Team"
            Else
                ' "Admin", "Site"
                action = "All"
            End If
        Else
            ' leave as is
        End If

        ' used in the sorting of views for Messages
        If (Not Request.QueryString("sort") Is Nothing) Then
            sort = Request.QueryString("sort").ToString()

            If sort = "IndexA" Or sort = "IndexD" Then
                System.Web.HttpContext.Current.Session(“Index1Sort”) = sort
                System.Web.HttpContext.Current.Session(“Index2Sort”) = sort
                System.Web.HttpContext.Current.Session(“Index3Sort”) = sort
            ElseIf sort = "ProcessA" Or sort = "ProcessD" Then
                System.Web.HttpContext.Current.Session(“ProcessSort”) = sort
            ElseIf sort = "LocationA" Or sort = "LocationD" Then
                System.Web.HttpContext.Current.Session(“Location1Sort”) = sort
                System.Web.HttpContext.Current.Session(“Location2Sort”) = sort
                System.Web.HttpContext.Current.Session(“Location3Sort”) = sort
                System.Web.HttpContext.Current.Session(“Location4Sort”) = sort
                System.Web.HttpContext.Current.Session(“Location5Sort”) = sort
            ElseIf sort = "TeamA" Or sort = "TeamD" Then
                System.Web.HttpContext.Current.Session(“Team1Sort”) = sort
                System.Web.HttpContext.Current.Session(“Team2Sort”) = sort
                System.Web.HttpContext.Current.Session(“Team3Sort”) = sort
                System.Web.HttpContext.Current.Session(“Team4Sort”) = sort
                System.Web.HttpContext.Current.Session(“Team5Sort”) = sort
            ElseIf sort = "LastNameA" Or sort = "LastNameD" Then
                System.Web.HttpContext.Current.Session(“LastName1Sort”) = sort
                System.Web.HttpContext.Current.Session(“LastName2Sort”) = sort
                System.Web.HttpContext.Current.Session(“LastName3Sort”) = sort
                System.Web.HttpContext.Current.Session(“LastName4Sort”) = sort
            ElseIf sort = "LastFourA" Or sort = "LastFourD" Then
                System.Web.HttpContext.Current.Session(“LastFour1Sort”) = sort
                System.Web.HttpContext.Current.Session(“LastFour2Sort”) = sort
            End If
        Else
            sort = ""

            'reset sorting options -

            ' Message Index sorting
            System.Web.HttpContext.Current.Session(“Index1Sort”) = "IndexD"
            System.Web.HttpContext.Current.Session(“Index2Sort”) = "IndexD"
            System.Web.HttpContext.Current.Session(“Index3Sort”) = "IndexD"
            ' Assigned sorting
            System.Web.HttpContext.Current.Session(“ProcessSort”) = "ProcessD"
            ' Location sorting
            System.Web.HttpContext.Current.Session(“Location1Sort”) = "LocationA"
            System.Web.HttpContext.Current.Session(“Location2Sort”) = "LocationA"
            System.Web.HttpContext.Current.Session(“Location3Sort”) = "LocationA"
            System.Web.HttpContext.Current.Session(“Location4Sort”) = "LocationA"
            System.Web.HttpContext.Current.Session(“Location5Sort”) = "LocationA"
            ' Team sorting
            System.Web.HttpContext.Current.Session(“Team1Sort”) = "TeamA"
            System.Web.HttpContext.Current.Session(“Team2Sort”) = "TeamA"
            System.Web.HttpContext.Current.Session(“Team3Sort”) = "TeamA"
            System.Web.HttpContext.Current.Session(“Team4Sort”) = "TeamA"
            System.Web.HttpContext.Current.Session(“Team5Sort”) = "TeamA"
            ' Last Name
            System.Web.HttpContext.Current.Session(“LastName1Sort”) = "LastNameA"
            System.Web.HttpContext.Current.Session(“LastName2Sort”) = "LastNameA"
            System.Web.HttpContext.Current.Session(“LastName3Sort”) = "LastNameA"
            System.Web.HttpContext.Current.Session(“LastName4Sort”) = "LastNameA"
            ' Last Four SSN
            System.Web.HttpContext.Current.Session(“LastFour1Sort”) = "LastFourA"
            System.Web.HttpContext.Current.Session(“LastFour2Sort”) = "LastFourA"
        End If

        ' because cLng("") is page error,  NULL I to be "0"
        If I = "" Then
            I = "0"
        End If
        If IsNumeric(I) Then
            LongI = CLng(I)
        Else
            Response_WriteLine("<p><font color=""red"">Warning:  Invalid Index chosen. Try again.</font></p>")
            I = "0"
            LongI = CLng(0)
        End If

        '
        ' BEGIN TITLE BARS
        '
        Response_WriteLine("<table width=""100%"" cellpadding=""2"" cellspacing=""0"">")
        ' Menu Bar: View Active Messages

        ' only show Site choice if AdminSite = "000".  If AdminSite = a specific site code, then don't give Site choices
        ' ***** If member is in multiple sites, then may need to adjust this port of code.
        ' ***** or put them in the Admins table instead ???

        Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #dbe4f0;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
        Response_WriteLine("<div class=""container-fluid"">")
        Response_WriteLine("<div class=""navbar-header"">")
        Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
        Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
        Response_WriteLine("<span class=""icon-bar""></span>")
        Response_WriteLine("<span class=""icon-bar""></span>")
        Response_WriteLine("<span class=""icon-bar""></span>")
        Response_WriteLine("</button>")
        Response_WriteLine("<a class=""navbar-brand"" href=""#""><b><u><i>Choose Site:</i></u></b></a>")
        Response_WriteLine("</div>")
        Response_WriteLine("<div class=""navbar-collapse collapse"">")
        Response_WriteLine("<ul class=""nav navbar-nav"">")

        MyCommand.CommandText = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' AND tab_Sites.Si_Active = 'Yes' AND tab_Sites.Si_SiteNum IN(" & Me.AdminSites & ") ORDER BY tab_Sites.Si_Name;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows Then
                sqlDataReader.Read()
                Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&refresh=True&S=" & sqlDataReader.Item("Si_SiteNum") & "&action=" & action & """>")
                If sqlDataReader.Item("Si_SiteNum") = S Then
                    Response_WriteLine("<big><b>" & sqlDataReader.Item("Si_Name") & "</b></big>")
                Else
                    Response_WriteLine("" & sqlDataReader.Item("Si_Name") & "")
                End If
                Response_WriteLine("</a></li>")
                While sqlDataReader.Read = True
                    Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&refresh=True&S=" & sqlDataReader.Item("Si_SiteNum") & "&action=" & action & """>")
                    If sqlDataReader.Item("Si_SiteNum") = S Then
                        Response_WriteLine("<big><b>" & sqlDataReader.Item("Si_Name") & "</b></big>")
                    Else
                        Response_WriteLine("" & sqlDataReader.Item("Si_Name") & "")
                    End If
                    Response_WriteLine("</a></li>")
                End While
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        Response_WriteLine("</ul></div></div></nav>")

        ' Menu Bar: Only show if in the "Admin Menu" Menu bar
        If menu = "Admin" Or menu = "Audit" Or menu = "History" Or menu = "Flagged" Or menu = "Reports" Then
            Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #dbe4f0;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
            Response_WriteLine("<div class=""container-fluid"">")
            Response_WriteLine("<div class=""navbar-header"">")
            Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
            Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
            Response_WriteLine("<span class=""icon-bar""></span>")
            Response_WriteLine("<span class=""icon-bar""></span>")
            Response_WriteLine("<span class=""icon-bar""></span>")
            Response_WriteLine("</button>")
            Response_WriteLine("<a class=""navbar-brand"" href=""#""><b><u><i>Admin Menu:</i></u></b></a>")
            Response_WriteLine("</div>")
            Response_WriteLine("<div class=""navbar-collapse collapse"">")
            Response_WriteLine("<ul class=""nav navbar-nav"">")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Audit&S=" & S & "&action=" & action & """>")
            If menu = "Audit" Then
                Response_WriteLine("<big><b>Audit Log</b></big>")
            Else
                Response_WriteLine("Audit Log")
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=History&S=" & S & "&action=" & action & """>")
            If menu = "History" Then
                Response_WriteLine("<big><b>Processing History</b></big>")
            Else
                Response_WriteLine("Processing History")
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Flagged&S=" & S & "&action=" & action & """>")
            If menu = "Flagged" Then
                Response_WriteLine("<big><b>Flagged</b></big>")
            Else
                Response_WriteLine("Flagged")
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Reports&S=" & S & "&action=" & action & """>")
            If menu = "Reports" Then
                Response_WriteLine("<big><b>Reports</b></big>")
            Else
                Response_WriteLine("Reports")
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("</ul></div></div></nav>")
        End If

        ' Menu Bar: ALL or MY
        ' only Members have "My Messages", thus only show this option to the Members.
        ' Admins, Site have "All Messages" by default.
        ' Allow entry from email links:
        ' MessageAdmin/Message.asp?A=Admin&S=537&I=159029
        If menu = "Open" Or LongI > 0 Then
            Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #dbe4f0;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
            Response_WriteLine("<div class=""container-fluid"">")
            Response_WriteLine("<div class=""navbar-header"">")
            Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
            Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
            Response_WriteLine("<span class=""icon-bar""></span>")
            Response_WriteLine("<span class=""icon-bar""></span>")
            Response_WriteLine("<span class=""icon-bar""></span>")
            Response_WriteLine("</button>")
            Response_WriteLine("<a class=""navbar-brand"" href=""#""><b><u><i>Messages:</i></u></b></a>")
            Response_WriteLine("</div>")
            Response_WriteLine("<div class=""navbar-collapse collapse"">")
            Response_WriteLine("<ul class=""nav navbar-nav"">")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&refresh=True&S=" & S & "&action=My&sort=" & sort & """>")
            If action = "My" Then
                Response_WriteLine("<big><b>My Assigned</b></big>")
            Else
                Response_WriteLine("My Assigned")
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&refresh=True&S=" & S & "&action=Team&sort=" & sort & """>")
            If action = "Team" Then
                If Me.AdminTeam = -1 Then
                    Response_WriteLine("<big><b>My Teams</b></big>")
                Else
                    Response_WriteLine("<big><b>My Team</b></big>")
                End If
            Else
                If Me.AdminTeam = -1 Then
                    Response_WriteLine("My Teams")
                Else
                    Response_WriteLine("My Team")
                End If
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&menu=Open&refresh=True&S=" & S & "&action=All&sort=" & sort & """>")
            If action = "All" Then
                Response_WriteLine("<big><b>All</b></big>")
            Else
                Response_WriteLine("All")
            End If
            Response_WriteLine("</a></li>")
            Response_WriteLine("</ul></div></div></nav>")
            ' if server too busy in last 10 minutes, skip showing the count.  It can take 1.5 seconds to load this value
            sec = Me.SecSinceOverload()
            If sec >= 0 And sec < 600 Then
                ' too busy
            Else
                Select Case Me.AdminType
                    Case "All"
                        sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages WHERE tab_Messages.Msg_Completed IS NULL AND tab_Messages.Msg_SiteNum IN(" & Me.AdminSites & ")"
                    Case "None"
                        ' should this not give No counts???
                        sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages WHERE tab_Messages.Msg_Completed IS NULL"
                    Case Else
                        ' "PACT", "FEE", etc
                        sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT" & " FROM tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_Completed IS NULL AND tab_Locations.Lo_Type = '" & Replace(Me.AdminType, "'", "''") & "'"
                End Select
                If S = "" Then
                    sSqlString = sSqlString & ";"
                Else
                    sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "';"
                End If
                If _clsMessageVAR.BDebug = True Then
                    Response.Write("sSqlString=" & sSqlString & "<br>")
                End If

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Not sqlDataReader.HasRows Then
                        countOpen = -1
                    Else
                        sqlDataReader.Read()
                        ' total entries
                        countOpen = sqlDataReader.Item("THECOUNT")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                If countOpen <> -1 Then
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td><center>" & countOpen & " Open")
                End If
                If Me.SiteName = "" Then
                    Response_WriteLine("for All Sites")
                Else
                    Response_WriteLine("for " & Me.SiteName & "")
                End If
                Response_WriteLine("</center></td></tr>")
            End If ' 0 <= sec < 600
        End If ' menu = Open or viewing an Index

        ' Menu Bar: Toggle between Indexes for specific site
        ' this block is up here instead of in the Index showing area because it still falls within the title bars
        If menu = "Open" And LongI > 0 Then
            ' I chosen, so allow toggling

            navBar = ""
            If action = "My" Then
                ' this will get member's Messages spread across ALL tab_Sites.

                MyCommand.CommandText = "SELECT TOP 1 tab_Messages.Msg_Index FROM tab_Messages LEFT JOIN tab_Members" & " ON tab_Messages.Msg_TeamIndex = tab_Members.Me_TeamIndex" & " WHERE tab_Messages.Msg_Index < " & I & " AND" & " tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " ORDER BY tab_Messages.Msg_Index DESC;"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = False Then
                        navBar = "<font color=""gray"">Start</font> - "
                    Else
                        navBar = "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>Previous</a> - "
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                navBar = navBar & I & " - "

                MyCommand.CommandText = "SELECT TOP 1 tab_Messages.Msg_Index FROM tab_Messages LEFT JOIN tab_Members" & " ON tab_Messages.Msg_TeamIndex = tab_Members.Me_TeamIndex" & " WHERE tab_Messages.Msg_Index > " & I & " AND" & " tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " ORDER BY tab_Messages.Msg_Index ASC;"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = False Then
                        navBar = navBar & "<font color=""gray"">End</font>"
                    Else
                        navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>Next</a>"
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

            Else
                ' All Messages that are open
                sSqlString = "SELECT TOP 1 tab_Messages.Msg_Index FROM tab_Messages WHERE tab_Messages.Msg_Index < " & I
                If S = "" Then
                    ' no Site limitation
                Else
                    sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "'"
                End If
                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = False Then
                        navBar = "<font color=""gray"">Start</font> - "
                    Else
                        navBar = "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>Previous</a> - "
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                navBar = navBar & I & " - "

                sSqlString = "SELECT TOP 1 tab_Messages.Msg_Index FROM tab_Messages WHERE tab_Messages.Msg_Index > " & I
                If S = "" Then
                    ' no Site limitation
                Else
                    sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "'"
                End If
                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = False Then
                        navBar = navBar & "<font color=""gray"">End</font>"
                    Else
                        navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>Next</a>"
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

            End If
        End If
        Response_WriteLine("<tr bgcolor=""#eeeeee""><td><center>" & navBar & "</center></td></tr>")
        Response_WriteLine("</table>")
        ' 
        ' END TITLE BARS
        '

        '
        ' Admin Menu Choices
        '
        Dim cntr, bOKtoView
        bOKtoView = False
        Dim TransferSelect
        Dim AssignSelect
        Dim namelist, MSGemail
        Dim LocationSelect
        Dim TeamSelect
        Dim optionvalue
        Dim RType
        Dim blockSize
        Dim auditMSG
        Dim bInjectionFree
        auditMSG = ""

        ' sometimes NULL, so check for that to output &nbsp;
        Dim Comment ' Memo field so store it as variable before using it
        Dim MDt As String
        Dim MCompleted, MAssigned, MAction, MDetail, MTm, MUsername
        Dim AssignedName ' full name from function call with MAssigned

        If LongI > 0 Then
            ' Index "I" chosen, show it

            ' Pre-Process form submit changes
            ' form hidden name="ACACTION" value="Update"
            ' form checkbox name="form_CheckDone"
            ' form textarea name="form_Status"

            Dim ACACTION, QSflag, PurgeDatePII
            Dim form_Transfer, form_Status, form_AssignTo, form_CheckDone, form_ReturnCall, form_Waiting

            Dim bFound
            Dim rsCompleted, rsAssigned, rsEmailSent, rsStatus, rsSiteNum, rsLocationIndex, rsTeamIndex
            Dim rsFullID, rsFirstName, rsLastName, rsLastFour, rsDateOfBirth, rsVendorName, rsVendorContactInfo, rsVendorTaxID, rsPhone
            Dim rsReturnCall, rsBestTime, rsMedChoice, rsMedName, rsReason, rsComment, rsDt, rsTm, rsUsername

            ' function call results to cache from the rs values
            Dim caLocationName, caTeamName

            Dim itemChanged, newSSI
            Dim SkipMoreEmails
            Dim AssignedTo, AssignedWarning
            Dim MSGdelay

            ACACTION = Request.Form("ACACTION")

            If (Not Request.QueryString("flag") Is Nothing) Then
                QSflag = Request.QueryString("flag").ToString()
            Else
                QSflag = ""
            End If

            MyCommand.CommandText = "SELECT * FROM tab_Messages WHERE tab_Messages.Msg_Index = " & I & ";"

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If sqlDataReader.Read = False Then
                    bFound = False
                Else
                    bFound = True
                    ' cache all entries so can close recordset immediately
                    'rsIndex not needed, "I" is used instead
                    rsCompleted = sqlDataReader.Item("Msg_Completed")
                    rsAssigned = sqlDataReader.Item("Msg_Assigned")
                    rsEmailSent = sqlDataReader.Item("Msg_EmailSent")
                    rsStatus = sqlDataReader.Item("Msg_Status")
                    rsSiteNum = sqlDataReader.Item("Msg_SiteNum")
                    rsLocationIndex = sqlDataReader.Item("Msg_LocationIndex")
                    rsTeamIndex = sqlDataReader.Item("Msg_TeamIndex")
                    rsFullID = sqlDataReader.Item("Msg_FullID")
                    rsFirstName = sqlDataReader.Item("Msg_FirstName")
                    rsLastName = sqlDataReader.Item("Msg_LastName")
                    rsLastFour = sqlDataReader.Item("Msg_LastFour")
                    rsDateOfBirth = sqlDataReader.Item("Msg_DOB")
                    rsVendorName = sqlDataReader.Item("Msg_VendorName")
                    rsVendorContactInfo = sqlDataReader.Item("Msg_VendorContactInfo")
                    rsVendorTaxID = sqlDataReader.Item("Msg_VendorTaxID")
                    rsPhone = sqlDataReader.Item("Msg_Phone")
                    rsReturnCall = sqlDataReader.Item("Msg_ReturnCall")
                    rsBestTime = sqlDataReader.Item("Msg_BestTime")
                    rsMedChoice = sqlDataReader.Item("Msg_MedChoice")
                    rsMedName = sqlDataReader.Item("Msg_MedName")
                    rsReason = sqlDataReader.Item("Msg_Reason")
                    rsComment = sqlDataReader.Item("Msg_Comment")
                    rsDt = sqlDataReader.Item("Msg_Dt")
                    rsTm = sqlDataReader.Item("Msg_Tm")
                    rsUsername = sqlDataReader.Item("Msg_Username")

                    '  some of potential NULL values to Nothing string for if clause usage
                    If IsDBNull(rsCompleted) Then rsCompleted = ""
                    If IsDBNull(rsAssigned) Then rsAssigned = ""
                    If IsDBNull(rsEmailSent) Then rsEmailSent = ""
                    If IsDBNull(rsStatus) Then rsStatus = ""
                    'rsSiteNum never NULL unless record was buggy
                    If IsDBNull(rsSiteNum) Then rsSiteNum = ""
                    'rsLocationIndex never NULL unless record was buggy
                    If IsDBNull(rsLocationIndex) Then rsLocationIndex = ""
                    'rsTeamIndex never NULL unless record was buggy
                    If IsDBNull(rsTeamIndex) Then rsTeamIndex = ""
                    If IsDBNull(rsFullID) Then rsFullID = ""
                    If IsDBNull(rsFirstName) Then rsFirstName = ""
                    If IsDBNull(rsLastName) Then rsLastName = ""
                    If IsDBNull(rsLastFour) Then rsLastFour = ""
                    If IsDBNull(rsDateOfBirth) Then rsDateOfBirth = "" Else rsDateOfBirth = CDate(rsDateOfBirth).ToShortDateString()
                    If IsDBNull(rsVendorName) Then rsVendorName = ""
                    If IsDBNull(rsVendorContactInfo) Then rsVendorContactInfo = ""
                    If IsDBNull(rsVendorTaxID) Then rsVendorTaxID = ""
                    If IsDBNull(rsPhone) Then rsPhone = ""
                    If IsDBNull(rsReturnCall) Then rsReturnCall = ""
                    If IsDBNull(rsBestTime) Then rsBestTime = ""
                    If IsDBNull(rsMedChoice) Then rsMedChoice = ""
                    If IsDBNull(rsMedName) Then rsMedName = ""
                    If IsDBNull(rsReason) Then rsReason = ""
                    If IsDBNull(rsBestTime) Then rsBestTime = ""
                    'rsDt never NULL
                    'rsTm never NULL
                    'rsUsername never null
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

            If bFound = True Then
                ' Location variables may change if transfered.  Default them to current settings
                caLocationName = Me.GetLocationName(rsLocationIndex)
                caTeamName = Me.GetTeamName(rsTeamIndex)
                RType = Me.GetTypeFromTeamIndex(rsTeamIndex)

                ' these values should be NULL but catch it anyway
                If caLocationName = "" Then caLocationName = "Nothing"
                If caTeamName = "" Then caTeamName = "Nothing"
                ' RType value of "Missing" is referenced later
                If RType = "" Then RType = "Missing"

                ' FLAG MENU
                If QSflag = "Yes" Then

                    form_flagOther = Request.Form("form_FlagOther")
                    bInjectionFree = Me.isValidsSqlString(form_flagOther)
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("bInjectionFree=" & bInjectionFree & ",form_flagOther=" & form_flagOther & "<br>")
                    End If
                    If bInjectionFree = False Then
                        Response_WriteLine("<p><font color=orange><b>Invalid Flag Comment, not storing.<br>")
                        Response_WriteLine("Correct the text and submit again.</b></font></p>")
                    End If

                    If Request.Form("form_FlagUsed") = "FormSubmitted" And bInjectionFree = True Then
                        Dim flagInfoE, flagInfoA
                        ' E and A (email and audit) = different because the email won't contain the free text comment as it could contain PII
                        flagInfoE = ""
                        flagInfoA = ""
                        ' see if Flags are checked
                        sSqlString = "SELECT tab_Flags.Fl_SortOrder, tab_Flags.Fl_Flag FROM tab_Flags WHERE tab_Flags.Fl_Type = '" & RType & "' ORDER BY Fl_SortOrder;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows Then
                                flagInfoE = "Message Created By " & rsUsername & " - " & Me.PollMemberNameForLogin(rsUsername) & vbCrLf
                                While sqlDataReader.Read = True
                                    If Request.Form("form_FlagCheck_" & sqlDataReader.Item("Fl_SortOrder")) = "on" Then
                                        flagInfoE = flagInfoE & sqlDataReader.Item("Fl_Flag") & vbCrLf
                                        flagInfoA = flagInfoA & sqlDataReader.Item("Fl_Flag") & vbCrLf
                                    End If
                                End While
                                If form_flagOther <> "" Then
                                    flagInfoE = flagInfoE & "Free text comment entered, open request to view the escalation reason in the audit history." & vbCrLf
                                    flagInfoA = flagInfoA & form_flagOther & vbCrLf
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        If flagInfoA = "" Then
                            Response_WriteLine("<br><font color=""red"">The form was submitted but nothing was chosen.<br>")
                            Response_WriteLine("Click <A HREF=""javascript:history.back()"">Back</A> and try again.</font><br>")
                        Else
                            ' send to:
                            ' 000 Admin or 000 Site or nnn Admin or nnn Site
                            ' and Adm_Type matches message's Type or is "All"
                            ' and Adm_Email IS NOT NULL
                            ' FlagOn = "Yes"

                            namelist = ""
                            sSqlString = "SELECT tab_Admins.Adm_Email FROM tab_Admins" & " WHERE tab_Admins.Adm_Email IS NOT NULL" & " AND (tab_Admins.Adm_Type = '" & RType & "' OR tab_Admins.Adm_Type = 'All')" & " AND (tab_Admins.Adm_SiteNum = '" & rsSiteNum & "' OR tab_Admins.Adm_SiteNum = '000')" & " AND tab_Admins.Adm_FlagOn = 'Yes'" & " ORDER BY tab_Admins.Adm_SiteNum DESC, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Email;"
                            'On Error Resume Next

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    Response_WriteLine("<p><font color=""red"">Error loading flag email recipients from database.</font></p>")
                                Else
                                    While sqlDataReader.Read = True
                                        If namelist = "" Then
                                            namelist = sqlDataReader.Item("Adm_Email")
                                        Else
                                            namelist = namelist & "; " & sqlDataReader.Item("Adm_Email")
                                        End If
                                    End While
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try
                            'On Error GoTo 0

                            sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'Flag', 'Flagged by " & Replace(Me.UserName, "'", "''") & vbCrLf
                            If namelist = "" Then
                                sSqlString = sSqlString & Replace(flagInfoA, "'", "''")
                            Else
                                sSqlString = sSqlString & Replace(Replace(namelist, "; ", vbCrLf), "'", "''") & vbCrLf & Replace(flagInfoA, "'", "''")
                            End If
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & "', '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                            Else
                                sSqlString = sSqlString & "', #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                            End If
                            sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                            If Not InsertTableRecord(sSqlString) Then
                                Response_WriteLine("<p><font color=""red"">Error inserting flag message into Audit</font></p>")
                            End If

                            If namelist = "" Then
                                ' no defined escalation recipients
                                Response_WriteLine("<p><font color=navy>Not sending <i>Flag</i> email, no supervisors are defined for this site.<br>")
                                Response_WriteLine("<br>")
                                Response_WriteLine("You'll need to verbally communicate escalation information about this message.</font></p>")
                            Else
                                ' valid TO list, so send email

                                MSGemail = "Message for " & caLocationName & " - " & caTeamName & "<br>" & vbCrLf & "Message Flagged for Supervisor Review by " & Me.UserName & " - " & Me.PollMemberNameForLogin(Me.UserName) & ":<br>" & vbCrLf & Replace(flagInfoE, vbCrLf, "<br>" & vbCrLf) & "<br>" & vbCrLf & "Reason: " & GetMessageReason(I) & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & "</a>" & "<br>" & vbCrLf

                                If Me.SendTheMessage(namelist, MSGemail) = True Then
                                    ' good, message sent
                                    Response.Write("<p><font color=green><i>Flag</i> email sent.  Supervisors notified of the status update.</font></p>")
                                Else
                                    ' bad, message send failure
                                    Response.Write("<p><font color=red>Error: Flag email send failure.  Supervisors not notified of the status update.</font></p>")
                                End If
                            End If
                        End If ' flagInfoA = ""
                    End If ' bInjectionFree = false

                    If bInjectionFree = True Or (Request.Form("form_FlagUsed") = "FormSubmitted" And bInjectionFree = False) Then
                        If RType = "Missing" Then
                            sSqlString = "SELECT tab_Flags.Fl_SortOrder, tab_Flags.Fl_Type, tab_Flags.Fl_Flag FROM tab_Flags ORDER BY tab_Flags.Fl_Type, tab_Flags.Fl_SortOrder;"
                        Else
                            sSqlString = "SELECT tab_Flags.Fl_SortOrder, tab_Flags.Fl_Type, tab_Flags.Fl_Flag FROM tab_Flags WHERE tab_Flags.Fl_Type = '" & RType & "' ORDER BY tab_Flags.Fl_SortOrder;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows Then
                                Response_WriteLine("<br>")
                                Response_WriteLine("<div class=""container-fluid"">")
                                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                Response_WriteLine("<table><tr><td>")
                                Response_WriteLine("<form name=""frm_MSG_FLAG"" method=""POST"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&I=" & I & "&action=" & action & "&flag=Yes"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_FlagUsed"" value=""FormSubmitted"">")
                                Response_WriteLine("Flag for supervisory review.  Check any that apply and submit:<br>")
                                Response_WriteLine("<br>")
                                While sqlDataReader.Read = True
                                    If sqlDataReader.Item("Fl_Flag") = "Other" Then
                                        Response_WriteLine("<font color=""green"">Other:</font> <input type=""text"" name=""form_FlagOther"" class=""form-control"" value=""" & Replace(form_flagOther, """", "&#34;") & """ size=""60""><br>")
                                    Else
                                        Response_WriteLine("<div class=""checkbox""><label><input type=""checkbox"" ")
                                        If Request.Form("form_FlagCheck_" & sqlDataReader.Item("Fl_SortOrder")) = "on" Then
                                            Response_WriteLine("checked ")
                                        End If
                                        Response_WriteLine("name=""form_FlagCheck_" & sqlDataReader.Item("Fl_SortOrder") & """> ")
                                        Response_WriteLine("<font color=""green"">" & sqlDataReader.Item("Fl_Flag") & "</font></label></div><br>")
                                    End If
                                End While
                                Response_WriteLine("<br>")
                                Response_WriteLine("<input type=""submit"" name=""S2"" class=""btn btn-primary"" value=""Submit""> Supervisor will follow-up with patient or message creater")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</td></tr></table></div></div>")
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If

                    ' show no more about the message, only the Flag form is shown.
                    Response_WriteLine("<p><a href=""JavaScript:window.close()"">Close Window</a></p>")
                Else ' QSflag = "Yes"
                    ' Flag Not Used, check for updates

                    ' EDIT START
                    If ACACTION = "Update" Then
                        ' form submit clicked

                        form_AssignTo = Request.Form("form_AssignTo")
                        form_Transfer = Request.Form("form_Transfer")
                        form_CheckDone = Request.Form("form_CheckDone")
                        form_ReturnCall = Request.Form("form_ReturnCall")
                        form_Waiting = Request.Form("form_Waiting")
                        form_Status = Request.Form("form_Status")

                        itemChanged = False
                        SkipMoreEmails = "no"

                        ' newSSI represent the target Location of a transfer, as the Team was chosen
                        ' so compute the LocationIndex as it may be different
                        ' first  newSSI to be the current LocationIndex
                        If rsLocationIndex = 0 Then
                            newSSI = 0
                        Else
                            newSSI = rsLocationIndex
                        End If

                        ' form_Transfer = the new "tab_Teams.Te_Index" value from the form dropdown
                        'Response.Write("form_Transfer=" & form_Transfer & "<br>")
                        If form_Transfer <> "" Then
                            ' changed from default value, store and audit.

                            ' Transfer means update LocationIndex variables to new values
                            ' because tab_Messages.Msg_LocationIndex might now be different
                            newSSI = Me.GetLocationIndex(form_Transfer)

                            ' audit entry using old names and values, and new names and values
                            sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'Transfer', 'NEW: " & Replace(Me.GetLocationName(newSSI), "'", "''") & " - " & Replace(Me.GetTeamName(form_Transfer), "'", "''") & vbCrLf & "OLD: " & Replace(caLocationName, "'", "''") & " - " & Replace(caTeamName, "'", "''")
                            If rsAssigned <> "" Then
                                ' will be clearing that field so add it to Audit
                                sSqlString = sSqlString & vbCrLf & "OLD Assignment: " & Replace(rsAssigned, "'", "''")
                            End If
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & "', '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                            Else
                                sSqlString = sSqlString & "', #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                            End If
                            sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                            If Not InsertTableRecord(sSqlString) Then
                                ' error storing Audit Insert record
                                Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit Transfer Insert, 1st attempt<br>", False, False)
                            End If

                            ' it's possible that new Team is in different Location, so update that too
                            UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_LocationIndex = " & newSSI & " WHERE tab_Messages.Msg_Index = " & I & ";")

                            ' update TeamIndex to transfer team's index
                            UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_TeamIndex = " & form_Transfer & " WHERE tab_Messages.Msg_Index = " & I & ";")

                            ' it's possible the Assignee had a value, so wipe that since it's now a different Team
                            If rsAssigned <> "" Then
                                UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Assigned = NULL WHERE tab_Messages.Msg_Index = " & I & ";")

                                Response.Write("<p>Index " & I & " Assigment to " & rsAssigned & " has been cleared due to <i>Transfer</i>.</p>")

                                ' clear out the rsAssigned variable now that it has been blanked
                                rsAssigned = ""
                                ' clear out what the form field was  to
                                form_AssignTo = ""
                            End If

                            '  the original message's Location/Team values to be those of the transfer as now the message has that setting
                            rsLocationIndex = newSSI
                            rsTeamIndex = form_Transfer
                            caLocationName = Me.GetLocationName(rsLocationIndex)
                            caTeamName = Me.GetTeamName(rsTeamIndex)

                            itemChanged = True
                            Response.Write("<p>Index " & I & " <i>Transferred</i>.</p>")

                            If SkipMoreEmails = "no" Then
                                ' now email the Members with EmailNew="Yes" of the transfer
                                ' Team is guaranteed active else couldn't transfer to it.

                                namelist = Me.GetTeamMemberNewEmails(form_Transfer)
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("Transfer:namelist=" & namelist & "<br>")
                                End If
                                If namelist = "" Then
                                    ' no active Team, or no emails listed for them
                                    Response.Write("<p><font color=navy>Note: Not sending email, no recipients defined.</font></p>")
                                Else
                                    ' valid TO list, so send email
                                    MSGemail = "Message for " & caLocationName & " - " & caTeamName & "<br>" & vbCrLf & "Message Transferred: " & theDate & " @ " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>" & vbCrLf & "Reason: " & GetMessageReason(I) & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & "</a>" & "<br>" & vbCrLf & "<br>" & vbCrLf & "To process the information, click the above link.  Login with your network account." & "<br>" & vbCrLf

                                    If Me.SendTheMessage(namelist, MSGemail) = True Then
                                        ' good, message sent
                                        Response.Write("<p><font color=green>Message <i>Transfer</i> email sent.  Receiving Team emailed.</font></p>")
                                        ' don't send more email for other updates - new transfer recipients is good enough
                                        SkipMoreEmails = "transfer"
                                    Else
                                        ' bad, message send failure
                                        Response.Write("<p><font color=red>Error: Message <i>Transfer</i> email send failure, email could not be sent at this time.</font></p>")
                                    End If
                                End If
                            Else
                                Response.Write("<p><font color=navy>Note: Not sending Message <i>Transfer</i> email for " & SkipMoreEmails & " Message.</font></p>")
                            End If ' SkipMoreEmails


                            If UCase(form_AssignTo) <> UCase(rsAssigned) Then
                                ' display warning that cannot Assign when Transfer was selected
                                Response.Write("<p><font color=red>Warning: Cannot simulaneously <i>Assign</i> and <i>Transfer</i>.  Message transferred but not assigned.</font></p>")
                            End If


                            If form_CheckDone = "on" Then
                                ' display warning that cannot Complete when Transfer was selected
                                Response.Write("<p><font color=red>Warning: Cannot simulaneously <i>Complete</i> and <i>Transfer</i>.  Message transferred but not completed.</font></p>")
                            End If

                        Else
                            ' not a transfer, so it's safe to check for AssignTo and Completion

                            ' check for close next, as if it is closed then don't send more emails
                            'Response.Write("form_CheckDone=" & form_CheckDone & "<br>")
                            If form_CheckDone = "on" Then
                                ' Completed checkbox is checked 

                                ' generate Audit for completion
                                sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Dt, Au_Tm, Au_Username, Au_IP) VALUES (" & I & ", 'Completed'"
                                ' #date# for access, 'date' for sSqlString
                                If _clsMessageVAR.BUsesSqlString = True Then
                                    sSqlString = sSqlString & ", '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                                Else
                                    sSqlString = sSqlString & ", #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                                End If
                                sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                                If Not InsertTableRecord(sSqlString) Then
                                    ' error storing Copmletion Audit record
                                    Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit Completion Insert, 1st attempt<br>", False, False)
                                End If

                                ' store completion update
                                UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Completed = 'Yes' WHERE tab_Messages.Msg_Index = " & I & ";")

                                ' change rsCompleted to the new value
                                rsCompleted = "Yes"

                                itemChanged = True
                                ' don't send status/transfer emails as it's now closed
                                SkipMoreEmails = "closed"
                                Response.Write("<p>Index " & I & "  to <i>Complete</i>.</p>")
                            End If

                            ' update the AssignTo field if it was changed, even if Done was checked
                            'Response.Write("form_AssignTo=" & form_AssignTo & "<br>")
                            If UCase(form_AssignTo) <> UCase(rsAssigned) Then
                                ' something changed, store it
                                If form_AssignTo = "" Then

                                    ' Audit the NULL assignee
                                    sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'Assigned', 'Field Cleared from " & rsAssigned
                                    ' #date# for access, 'date' for sSqlString
                                    If _clsMessageVAR.BUsesSqlString = True Then
                                        sSqlString = sSqlString & "', '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                                    Else
                                        sSqlString = sSqlString & "', #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                                    End If
                                    sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                                    If Not InsertTableRecord(sSqlString) Then
                                        ' error storing Audit Assignee cleared Insert record
                                        Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit-Assignee-Cleared Insert, 1st attempt<br>", False, False)
                                    End If

                                    ' store NULL assignee
                                    UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Assigned = NULL WHERE tab_Messages.Msg_Index = " & I & ";")

                                    itemChanged = True
                                    Response.Write("<p>Index " & I & " <i>Assign To</i> field cleared.</p>")

                                Else

                                    ' first ensure new Assignee is still a team member of the assigned team.
                                    ' previous error sequence:  
                                    ' 9:30a message assgined to user A, team A by user X
                                    ' 10:30a message transferred to team B, (assignment NULL)
                                    ' 2:00p message user X hit refresh and it assigned again, this time user A not part of team B
                                    If Me.isUserNameOnTeam(form_AssignTo, rsTeamIndex) = False Then
                                        Response.Write("<p><font color=red>Error: Attempting to assign Message to Member that is not Active on Team Anymore.<br>Try again with udpated assigment list.</font></p>")
                                    Else

                                        ' audit the new assignee
                                        sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'Assigned', 'Set to " & form_AssignTo
                                        ' #date# for access, 'date' for sSqlString
                                        If _clsMessageVAR.BUsesSqlString = True Then
                                            sSqlString = sSqlString & "', '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                                        Else
                                            sSqlString = sSqlString & "', #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                                        End If
                                        sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                                        If Not InsertTableRecord(sSqlString) Then
                                            ' error storing Audit Assignee changed Insert record
                                            Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit-Assignee-Changed Insert, 1st attempt<br>", False, False)
                                        End If

                                        ' store new assignee
                                        UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Assigned = '" & form_AssignTo & "' WHERE tab_Messages.Msg_Index = " & I & ";")

                                        itemChanged = True
                                        If rsAssigned = "" Then
                                            Response.Write("<p>Index " & I & " <i>Assign To</i> " & Me.GetMemberNameFromUandTI(form_AssignTo, rsTeamIndex) & "</p>")
                                        Else
                                            Response.Write("<p>Index " & I & " changed, <i>Assign To</i> " & Me.GetMemberNameFromUandTI(form_AssignTo, rsTeamIndex) & " from " & Me.GetMemberNameFromUandTI(rsAssigned, rsTeamIndex) & "</p>")
                                        End If

                                        ' Only send email if assigned to someone other than logged in user
                                        If SkipMoreEmails = "no" Then
                                            If UCase(Me.UserName) = UCase(form_AssignTo) Then
                                                ' same person, no email
                                                Response.Write("<p><font color=navy>Note: Not sending Message Assignment email to SELF.</font></p>")
                                            Else
                                                ' now email the tab_Members.Me_Email recipient of the asignment  (just the ASSIGNEE - not the other members)
                                                sSqlString = "SELECT tab_Members.Me_Email FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & rsTeamIndex & " AND tab_Members.Me_Username LIKE '" & form_AssignTo & "'" & " AND tab_Members.Me_EmailAssign = 'Yes'" & " ORDER BY tab_Members.Me_Active DESC;"

                                                MyCommand.CommandText = sSqlString

                                                Try
                                                    If MyConnection.State = ConnectionState.Closed Then
                                                        MyConnection.Open()
                                                    End If

                                                    sqlDataReader = MyCommand.ExecuteReader

                                                    namelist = ""
                                                    While sqlDataReader.Read = True
                                                        If namelist = "" Then
                                                            namelist = sqlDataReader.Item("Me_Email")
                                                        Else
                                                            namelist = namelist & "; " & sqlDataReader.Item("Me_Email")
                                                        End If
                                                    End While

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("Assign:namelist=" & namelist & "<br>")
                                                End If
                                                If namelist = "" Then
                                                    ' no active Team
                                                    Response.Write("<p><font color=green>Not emailing the assignee, assignment emails are turned off</font></p>")
                                                Else
                                                    ' valid TO list, so send email
                                                    MSGemail = "Message for " & caLocationName & " - " & caTeamName & "<br>" & vbCrLf & "Message Assigned to " & Me.GetMemberNameFromUandTI(form_AssignTo, rsTeamIndex) & ": " & theDate & " @ " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>" & vbCrLf & "Reason: " & GetMessageReason(I) & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & "</a>" & "<br>" & vbCrLf & "<br>" & vbCrLf & "To process the information, click the above link.  Login with your network account." & "<br>" & vbCrLf

                                                    If Me.SendTheMessage(namelist, MSGemail) = True Then
                                                        ' good, message sent
                                                        Response.Write("<p><font color=green>Message Assignment email sent.  Member notified of the message assignment.</font></p>")
                                                        ' don't send more email for other updates - new assignee recipients is good enough
                                                        SkipMoreEmails = "Assignment"
                                                    Else
                                                        ' bad, message send failure
                                                        Response.Write("<p><font color=red>Error: Message Assignment email send failure.  Member not notified of the assignment.</font></p>")
                                                    End If
                                                End If
                                            End If ' UserName = formAssignTo
                                        Else
                                            Response.Write("<p><font color=navy>Note: Not sending Message Assignment email for " & SkipMoreEmails & " Message.</font></p>")
                                        End If ' SkipMoreEmails

                                    End If   ' form_Assigned = ""

                                    ' update rsAssigned value with the new one
                                    rsAssigned = form_AssignTo

                                End If ' isUserNameOnTeam
                            Else
                                ' same, skip
                            End If  ' form_AssignTo <> rsAssigned

                        End If ' form_Transfer

                        ' Check for new "ReturnCall" {on, ""} regardless of Transfer values
                        If form_ReturnCall = "" And form_Waiting = "Waiting" Then
                            ' unchecked = "" so verify the hidden value form_Waiting was shown

                            ' audit entry for ReturnCall field update
                            sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'ReturnCall Updated', 'NEW: Yes" & vbCrLf & "OLD: Waiting', "
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & "'" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                            Else
                                sSqlString = sSqlString & "#" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                            End If
                            sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                            If Not InsertTableRecord(sSqlString) Then
                                ' error storing ReturnCall Insert Audit record
                                Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit ReturnCall Insert, 1st attempt<br>", False, False)
                            End If

                            ' ReturnCall checkbox is checked 
                            UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_ReturnCall = 'Yes' WHERE tab_Messages.Msg_Index = " & I & ";")

                            ' don't trigger email sending for Waiting toggles
                            ' SkipMoreEmails = ... not  here ...

                            ' update rsReturnCall as it's now been changed
                            rsReturnCall = "Yes"

                            itemChanged = True
                            Response.Write("<p>Index " & I & " <i>Return Call</i> changed from Waiting to Yes.</p>")
                        Else
                            ' kept it checked, or field not shown - do nothing
                        End If

                        ' store status updates regardless of Completion, AssignTo, or Transfer
                        'Response.Write("form_Status=" & form_Status & "<br>")
                        If rsStatus = form_Status Then
                            ' SAME, skip it
                        Else

                            ' store the new Status message in audit record

                            bInjectionFree = Me.isValidsSqlString(form_Status)
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("bInjectionFree=" & bInjectionFree & ",form_Status=" & form_Status & "<br>")
                            End If
                            If bInjectionFree = False Then
                                Response_WriteLine("<p><font color=""orange""><b>Invalid Data in the Status field, not storing the Status Update.<br>")
                                Response_WriteLine("Change the wording and submit again.</b></font></p>")
                                ' update rsStatus with new value so it is defaulted in the text area to be submitted again.
                                rsStatus = form_Status
                            Else

                                ' DIFFERENT, store it
                                If form_Status = "" Then

                                    sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'Status Updated', 'Nothing', "
                                    ' #date# for access, 'date' for sSqlString
                                    If _clsMessageVAR.BUsesSqlString = True Then
                                        sSqlString = sSqlString & "'" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                                    Else
                                        sSqlString = sSqlString & "#" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                                    End If
                                    sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                                    If Not InsertTableRecord(sSqlString) Then
                                        ' error storing Status Update Audit record
                                        Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit Status Nothing Insert, 1st attempt<br>", False, False)
                                    End If

                                    ' Nothing out the field.
                                    UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Status = NULL WHERE tab_Messages.Msg_Index = " & I & ";")

                                    ' update rsStatus with new value
                                    rsStatus = ""

                                Else

                                    sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Detail, Au_Dt, Au_Tm, Au_Username, Au_IP)" & " VALUES (" & I & ", 'Status Updated', '" & Replace(form_Status, "'", "''")
                                    ' #date# for access, 'date' for sSqlString
                                    If _clsMessageVAR.BUsesSqlString = True Then
                                        sSqlString = sSqlString & "', '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                                    Else
                                        sSqlString = sSqlString & "', #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                                    End If
                                    sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                                    If Not InsertTableRecord(sSqlString) Then
                                        ' error storing Status Update Audit record
                                        Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>The sSqlString string failed for Audit Status Insert, 1st attempt<br>", False, False)
                                    End If

                                    ' store a value
                                    UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Status = '" & Replace(form_Status, "'", "''") & "' WHERE tab_Messages.Msg_Index = " & I & ";")

                                    ' update rsStatus with new value
                                    rsStatus = form_Status

                                End If

                                itemChanged = True
                                Response.Write("<p>Index " & I & " <i>Status</i> updated.</p>")

                                If SkipMoreEmails = "no" Then

                                    ' if it's assigned, then only email the person assigned if different person did the status update
                                    ' reload the Assignee value as assignee could have changed by submitting the form
                                    sSqlString = "SELECT tab_Messages.Msg_Assigned FROM tab_Messages WHERE tab_Messages.Msg_Index = " & I & ";"

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = False Then
                                            ' strange, did not find index I
                                            AssignedTo = "None"
                                            Response.Write("<p><font color=red>Error: Index " & I & " not found.  Contact system administrator.</font></p>")
                                        Else
                                            If IsDBNull(sqlDataReader.Item("Msg_Assigned")) Then
                                                AssignedTo = "None"
                                            Else
                                                AssignedTo = sqlDataReader.Item("Msg_Assigned")
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("AssignedTo=" & AssignedTo & "<br>")
                                    End If

                                    If UCase(AssignedTo) = UCase(Me.UserName) Then
                                        Response.Write("<p><font color=navy>Not sending <i>Status Update</i> email as the Assignee performed the <i>Status Update</i>.</font></p>")
                                    Else

                                        If AssignedTo = "None" Then
                                            ' email this Team's tab_Members.Me_Email about the status change
                                            ' - only if EmailStatus="Yes" for this Status Update
                                            ' - do not include logged in user in email recipients
                                            sSqlString = "SELECT tab_Members.Me_Email FROM tab_Members LEFT JOIN tab_Messages" & " ON tab_Members.Me_TeamIndex = tab_Messages.Msg_TeamIndex" & " WHERE tab_Messages.Msg_Index = " & I & " AND tab_Members.Me_Active = 'Yes' AND tab_Members.Me_EmailStatus = 'Yes'" & " AND tab_Members.Me_Username NOT LIKE '" & UCase(Me.UserName) & "'" & " ORDER BY tab_Members.Me_Email;"
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("email.all.non-self.members.sSqlString=" & sSqlString & "<br>")
                                            End If
                                        Else
                                            ' Messages is assigned so email only the assignee
                                            ' - only if EmailStatus="Yes" for this Status Update
                                            sSqlString = "SELECT tab_Members.Me_Email FROM tab_Members LEFT JOIN tab_Messages" & " ON tab_Members.Me_TeamIndex = tab_Messages.Msg_TeamIndex" & " WHERE tab_Messages.Msg_Index = " & I & " AND tab_Members.Me_Active = 'Yes' AND tab_Members.Me_EmailStatus = 'Yes'" & " AND tab_Members.Me_Username LIKE '" & UCase(AssignedTo) & "'" & " ORDER BY tab_Members.Me_Email;"
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("email.only.the.assignee.sSqlString=" & sSqlString & "<br>")
                                            End If
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            namelist = ""
                                            While sqlDataReader.Read = True
                                                If namelist = "" Then
                                                    namelist = sqlDataReader.Item("Me_Email")
                                                Else
                                                    namelist = namelist & "; " & sqlDataReader.Item("Me_Email")
                                                End If
                                            End While

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("Status:namelist=" & namelist & "<br>")
                                        End If
                                        If namelist = "" Then
                                            ' no active members
                                            Response.Write("<p><font color=navy>Not sending <i>Status Update</i> email, no available Team members.</font></p>")
                                        Else
                                            ' valid TO list, so send email
                                            MSGemail = "Message for " & Me.GetLocationName(rsLocationIndex) & " - " & caTeamName & "<br>" & vbCrLf & "Status Updated: " & theDate & " @ " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>" & vbCrLf & "Reason: " & GetMessageReason(I) & "<br>" & vbCrLf & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & """>" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & rsSiteNum & "&I=" & I & "</a>" & "<br>" & vbCrLf & "<br>" & vbCrLf & "To view the information, click the above link.  Login with your network account." & "<br>" & vbCrLf

                                            If Me.SendTheMessage(namelist, MSGemail) = True Then
                                                ' good, message sent
                                                Response.Write("<p><font color=green>Status update email sent.  Member(s) notified of the status update.</font></p>")
                                            Else
                                                ' bad, message send failure
                                                Response.Write("<p><font color=red>Error: status update email send failure.  Members not notified of the status update.</font></p>")
                                            End If
                                        End If ' namelist = ""
                                    End If ' SkipStatusEmail
                                Else
                                    Response.Write("<p><font color=navy>Note: Not sending Status Update email for " & SkipMoreEmails & " Message.</font></p>")
                                End If ' SkipMoreEmails

                            End If ' bInjectionFree

                        End If ' rsStatus

                        If itemChanged = True Then
                            ' Action Chosen, statement already displayed
                        Else
                            Response_WriteLine("<p><font color=""red"">Nothing Changed.  Submit button clicked but nothing was changed.</font></p>")
                        End If

                    End If ' ACACTION = "Update"		

                    ' END EDIT section

                    ' DISPLAY START	

                    ' RType is still valid from the submit section where it was first loaded
                    '  bOKtoView
                    '  override: always allow message creater to view it
                    If UCase(rsUsername) = UCase(Me.UserName) Then
                        bOKtoView = True
                    Else
                        '
                        ' RULE: Member for this sub-site can see ALL records for ALL Teams within this sub-site.
                        ' Member can see other sub-site records (cross coverage between CBOCs)
                        ' Member CANNOT see other site records (unless is a member there too)
                        '
                        If Me.AdminAccess = "Admin" Or Me.AdminAccess = "Site" Then
                            ' Admin can view this entire site and Locations
                            ' Site (Manager) can view this entire site and Locations
                            If Me.AdminSites.ToString.Contains("'" & rsSiteNum & "'") Or Me.AdminSite = rsSiteNum Then
                                bOKtoView = True
                            Else
                                ' "Site Admin" for another site, cannot view
                                ' "Site Manager" for another site, cannot view
                            End If
                        Else
                            If Me.AdminAccess = "Member" Then
                                If Me.DoesMemberSiteMatchMessageSite(rsLocationIndex) Then
                                    bOKtoView = True
                                Else
                                    ' member of another site can't view this site's messages
                                End If
                            Else
                                ' at this point AdminSite would be "None" but can't get into Admin Menu in that situation...
                            End If
                        End If
                        ' now for cases when approval was granted, check to see if Type matches (or is covered by "All")
                        If bOKtoView = True Then
                            If Me.AdminType <> "All" Then
                                ' don't need to lookup RTYpe as it already exists, else would be  Me.GetTypeFromLocationIndex (rsLocationIndex)
                                If Me.AdminType = RType Or RType = "Missing" Then
                                    ' true, matches, still OK
                                Else
                                    ' not OK, logged in user is of different AdminType
                                    bOKtoView = False
                                End If
                            End If
                        End If
                    End If ' username = username

                    If bOKtoView = True Then

                        If ACACTION <> "Update" And ACACTION <> "Flag" Then
                            ' has access to view AND Form submit NOT clicked
                            ' generate Audit record
                            sSqlString = "INSERT INTO tab_Audit (Au_IndexMessage, Au_Action, Au_Dt, Au_Tm, Au_Username, Au_IP) VALUES (" & I & ", 'Viewed', "
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & "'" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
                            Else
                                sSqlString = sSqlString & "#" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
                            End If
                            sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

                            If Not InsertTableRecord(sSqlString) Then
                                ' error storing Viewing Audit record.  Continue with Message processing.
                                Response_WriteLine("<p><font color=""red"">The sSqlString string failed for Audit View Insert</font></p>")
                            End If
                            auditMSG = auditMSG & "<p>Audit Record Generated for Viewing.</p>"
                        End If

                        ' preload assigned username's display name
                        If rsAssigned = "" Then
                            AssignedName = "&nbsp;"
                        Else
                            ' blank if invalid match
                            AssignedName = Me.GetMemberNameFromUandTI(rsAssigned, rsTeamIndex)
                            If AssignedName = "" Then
                                ' since blank,  it back to the Username that is stored in tab_Messages.Msg_Assigned
                                ' this is due to a member's row being deleted form the Members table
                                ' or the username renamed w/o changing corresponding Messages
                                AssignedName = "<font color=""red"">Warning:" & Me.CleanUserName(rsAssigned) & " is not a member anymore.</font>"
                                AssignedWarning = True
                            End If
                        End If

                        ' SHOW The Message
                        Response_WriteLine("<div class=""container-fluid"">")
                        Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                        Response_WriteLine("<p>")
                        Response_WriteLine("<table cellpadding=""0"" cellspacing=""0""><tr><td>")
                        Response_WriteLine("<table>")
                        ' a blank "" phone field indicates PII purged
                        If rsCompleted = "Yes" And rsPhone = "" Then
                            ' Message too old, has been purged
                            ' PurgeDatePII: if Today = 5/16/2012, 1st of month 6 months ago = 11/1/2011
                            PurgeDatePII = DateAdd("m", -6, theDate)
                            PurgeDatePII = CDate(DatePart("m", PurgeDatePII) & "/1/" & DatePart("yyyy", PurgeDatePII))
                            Response_WriteLine("<tr><td>Complete:</td><td>Yes</td></tr>")
                            Response_WriteLine("<tr><td valign=""top"" colspan=""2""><center>Message Completed prior to purge date " & PurgeDatePII & ", ")
                            Response_WriteLine("PII had been purged.</center></td></tr>")
                        Else
                            ' valid message, show all fields						
                            If rsCompleted = "Yes" Then
                                Response_WriteLine("<tr><td>Complete:</td><td>Yes</td></tr>")
                                Response_WriteLine("<tr><td valign=""top"" nowrap>Assigned To:</td><td><font color=""navy"">" & AssignedName & "</font></td></tr>")
                                Response_WriteLine("<tr><td valign=""top"">Status:</td><td>")
                                If rsStatus = "" Then
                                    Response_WriteLine("&nbsp;")
                                Else
                                    Response_WriteLine("<table border=1 bgcolor=""white"" cellpadding=""5"" cellspacing=""0"" bordercolor=""black""><tr><td><pre>" & rsStatus & "</pre></td></tr></table>")
                                End If
                                Response_WriteLine("</td></tr>")
                            Else
                                ' Show Form for updates by Admins or Members
                                ' Build a Team select box from all Active Teams for this Location
                                ' where Reason Type matches
                                ' this initial TransferSelect value, plus </select>, is used in an "if clause" below
                                TransferSelect = "<select name=""form_Transfer"" class=""form-control""><option selected></option>"
                                sSqlString = "SELECT tab_Teams.Te_Name, tab_Teams.Te_Index, tab_Locations.Lo_Name FROM tab_Teams LEFT JOIN tab_Locations" & " ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & rsSiteNum & "'"
                                If RType <> " " And RType <> "Missing" Then
                                    ' if erroneously TeamIndex was NULL then RType wouldn't be valid so don't limit Team choices
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                                End If
                                sSqlString = sSqlString & " AND tab_Teams.Te_Active = 'Yes' AND tab_Teams.Te_Index <> " & rsTeamIndex & " ORDER BY tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    While sqlDataReader.Read = True
                                        If sqlDataReader.Item("Te_Index") = rsTeamIndex Then
                                            ' skip, can't transfer to "Self"
                                            'Response.Write("skip self<br>")
                                        Else
                                            optionvalue = sqlDataReader.Item("Lo_Name") & " " & sqlDataReader.Item("Te_Name")
                                            namelist = Me.GetTeamMemberNames(sqlDataReader.Item("Te_Index"), False, False)
                                            If namelist <> "" Then
                                                optionvalue = optionvalue & " - " & namelist
                                            End If
                                            If Len(optionvalue) > 99 Then
                                                optionvalue = Left(optionvalue, 99) & "..."
                                            End If
                                            TransferSelect = TransferSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & """>" & optionvalue & "</option>" & vbCrLf
                                        End If
                                    End While

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                TransferSelect = TransferSelect & "</select>"

                                ' Build a member select box from all Active Members for this Location (regardless of ShowOn)
                                ' this initial AssignSelect value, plus </select>, is used in an "if clause" below
                                AssignSelect = "<select name=""form_AssignTo"" class=""form-control""><option selected></option>"
                                ' only offer SELF choice if the logged in Member/Admin is active member of this Team
                                sSqlString = "SELECT tab_Members.Me_Index FROM tab_Members WHERE tab_Members.Me_TeamIndex = "
                                If rsTeamIndex = 0 Then
                                    sSqlString = sSqlString & "0"
                                Else
                                    sSqlString = sSqlString & rsTeamIndex
                                End If
                                sSqlString = sSqlString & " AND tab_Members.Me_Username LIKE '" & Replace(Me.UserName, "'", "''") & "' AND tab_Members.Me_Active = 'Yes';"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If sqlDataReader.Read = True Then
                                        AssignSelect = AssignSelect & "<option value=""" & Me.UserName & """>SELF</option>" & vbCrLf
                                        AssignSelect = AssignSelect & "<option></option>" & vbCrLf
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                If rsTeamIndex = 0 Then
                                    ' strange - tab_Messages.Msg_TeamIndex should never be NULL
                                Else
                                    sSqlString = "SELECT tab_Members.Me_Username, tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & rsTeamIndex & " AND tab_Members.Me_Active = 'Yes' ORDER BY tab_Members.Me_SortOrder;"

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        While sqlDataReader.Read = True
                                            If UCase(sqlDataReader.Item("Me_Username")) = UCase(rsAssigned) Then
                                                ' already assigned to this person in the drop down, so select it.
                                                AssignSelect = Replace(AssignSelect, " selected", "")
                                                If IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                                    AssignSelect = AssignSelect & "<option value=""" & sqlDataReader.Item("Me_Username") & """ selected>" & sqlDataReader.Item("Me_Name") & "</option>" & vbCrLf
                                                Else
                                                    AssignSelect = AssignSelect & "<option value=""" & sqlDataReader.Item("Me_Username") & """ selected>" & sqlDataReader.Item("Me_Name") & " " & sqlDataReader.Item("Me_Title") & "</option>" & vbCrLf
                                                End If
                                            Else
                                                ' other usernames available
                                                If IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                                    AssignSelect = AssignSelect & "<option value=""" & sqlDataReader.Item("Me_Username") & """>" & sqlDataReader.Item("Me_Name") & "</option>" & vbCrLf
                                                Else
                                                    AssignSelect = AssignSelect & "<option value=""" & sqlDataReader.Item("Me_Username") & """>" & sqlDataReader.Item("Me_Name") & " " & sqlDataReader.Item("Me_Title") & "</option>" & vbCrLf
                                                End If
                                            End If
                                        End While

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End If
                                AssignSelect = AssignSelect & "</select>"
                                Response_WriteLine("<form name=""frm_MSG_ACTIONS"" method=""POST"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & """ onsubmit=""return Validate();"">")
                                Response_WriteLine("<input type=""hidden"" name=""ACACTION"" value=""Update"">")
                                If rsReturnCall = "Waiting" Then
                                    Response_WriteLine("<tr><td valign=""top"">Waiting:</td>")
                                    Response_WriteLine("<td><div class=""checkbox""><label><input type=""checkbox"" name=""form_ReturnCall"" checked>")
                                    Response_WriteLine("<font color=""green""> <small>When no longer waiting: Uncheck the box, indicate new instructions in Status, click ""Update"" button.</small></font></label></div>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Waiting"" value=""Waiting"">")
                                    Response_WriteLine("</td></tr>")
                                Else
                                    ' show nothing special
                                End If
                                Response_WriteLine("<tr><td valign=""top"">Assign To:</td>")
                                Response_WriteLine("<td><font color=""green""><small>Self-assign or direct the assignment to another Team Member.</small></font><br>")
                                If AssignSelect = "<select name=""form_AssignTo"" class=""form-control""><option selected></option></select>" Then
                                    Response_WriteLine("<br><font color=""red"">WARNING: Message is assigned to an invalid Team.<br>Transfer to another Team.</font>")
                                Else
                                    Response_WriteLine("" & AssignSelect & "")
                                    If AssignedWarning = True Then
                                        Response_WriteLine("<br><font color=""red"">WARNING: Message is assigned to " & rsAssigned & "<br>but is not a Team Member, choose another.</font><br>")
                                    End If
                                End If
                                Response_WriteLine("</td></tr>")
                                Response_WriteLine("<tr><td valign=""top"">Transfer:</td>")
                                Response_WriteLine("<td><font color=""green""><small>Redirect this Message to a different Team for processing.</small></font><br>")
                                If TransferSelect = "<select name=""form_Transfer"" class=""form-control""><option selected></option></select>" Then
                                    Response.Write("Cannot Transfer: No other Teams at " & Me.GetSiteName(rsSiteNum) & ".<br>")
                                Else
                                    Response.Write(TransferSelect)
                                End If
                                Response_WriteLine("</td>")
                                Response_WriteLine("</tr>")
                                Response_WriteLine("<tr><td valign=""top"">Status:</td><td>")
                                Response_WriteLine("<font color=""green""><small>Use this for status updates, reminders, notes, and closure info.</small></font><br>")
                                Response_WriteLine("<textarea name=""form_Status"" class=""form-control"" rows=""12"" cols=""80"">" & rsStatus & "</textarea></td></tr>")
                                Response_WriteLine("<tr><td valign=""top"">Complete:</td>")
                                Response_WriteLine("<td><div class=""checkbox""><label><input type=""checkbox"" name=""form_CheckDone"">")
                                Response_WriteLine("<font color=""green""><small>")
                                Response_WriteLine("To close this message:<br>")
                                Response_WriteLine("1.	Is this message completed to the patient's satisfaction?<br>")
                                Response_WriteLine("2.	Has all appropriate documentation been placed in CPRS?<br>")
                                Response_WriteLine("3.	If YES, check the Complete box and click the ""Update"" button.<br>")
                                Response_WriteLine("4.	If NO, DO NOT check as Complete")
                                Response_WriteLine("</small></font></label></div>")
                                Response_WriteLine("</td></tr>")
                                Response_WriteLine("<tr><td colspan=""2""><center><input type=""submit"" name=""SubmitUpdate"" class=""btn btn-primary"" id=""idSubmitUpdate"" value=""Update""></center></td></tr>")
                                Response_WriteLine("</form>")
                            End If ' rsCompleted = "Yes"

                            If rsComment <> "" Then
                                rsComment = Replace(rsComment, vbCrLf, "<br>")
                            End If
                            Response_WriteLine("<tr><td colspan=2><hr color=black></td></tr>")
                            If rsVendorName <> "" Then
                                Response_WriteLine("<tr><td nowrap>Vendor Name:</td><td>" & rsVendorName & "</td></tr>")
                            End If
                            If rsVendorContactInfo <> "" Then
                                Response_WriteLine("<tr><td nowrap>Vendor Contact Info:</td><td>" & rsVendorContactInfo & "</td></tr>")
                            End If
                            If rsVendorTaxID <> "" Then
                                Response_WriteLine("<tr><td nowrap>Vendor Tax ID:</td><td>" & rsVendorTaxID & "</td></tr>")
                            End If
                            If rsFullID <> "" Then
                                Response_WriteLine("<tr><td nowrap>Full ID:</td><td>" & rsFullID & "</td></tr>")
                            End If
                            If rsLastName <> "" Then
                                Response_WriteLine("<tr><td nowrap>Last Name:</td><td>" & rsLastName & "</td></tr>")
                            End If
                            If rsFirstName <> "" Then
                                Response_WriteLine("<tr><td nowrap>First Name:</td><td>" & rsFirstName & "</td></tr>")
                            End If
                            If rsLastFour <> "" Then
                                Response_WriteLine("<tr><td nowrap>Last Four:</td><td>" & rsLastFour & "</td></tr>")
                            End If
                            If Not IsDBNull(rsDateOfBirth) Then
                                Response_WriteLine("<tr><td nowrap>Date of Birth:</td><td>" & rsDateOfBirth & "</td></tr>")
                            End If
                            Response_WriteLine("<tr><td>Reason:</td><td>" & rsReason & "</td></tr>")
                            ' hard coded values for MedChoice
                            If rsMedChoice <> "" Then
                                Response_WriteLine("<tr><td>Med Choice:</td><td>" & rsMedChoice & "</td></tr>")
                            End If
                            If rsMedName <> "" Then
                                Response_WriteLine("<tr><td>Med Name:</td><td>" & rsMedName & "</td></tr>")
                            End If
                            Response_WriteLine("<tr><td valign=""top"">Comment:</td><td>" & rsComment & "</td></tr>")
                            Response_WriteLine("<tr><td>Phone:</td><td>" & rsPhone & "</td></tr>")
                            Response_WriteLine("<tr><td nowrap>Return Call:</td>")
                            If rsReturnCall = "Waiting" Then
                                Response_WriteLine("<td><font color=""red"">" & rsReturnCall & "</font></td>")
                            Else
                                Response_WriteLine("<td>" & rsReturnCall & "</td>")
                            End If
                            Response_WriteLine("</tr>")
                            If rsBestTime <> "" Then
                                Response_WriteLine("<tr><td nowrap>Best Time:</td><td>" & rsBestTime & "</td></tr>")
                            End If

                        End If ' Purged fields not shown
                        Response_WriteLine("<tr><td colspan=2><hr color=black></td></tr>")
                        Response_WriteLine("<tr><td valign=""top"">Team:</td><td>")
                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                            Response.Write(Me.ColorizeTeamName(caTeamName))
                        Else
                            Response.Write(Me.ColorizeFont(caTeamName))
                        End If
                        namelist = Me.GetTeamMemberNames(rsTeamIndex, False, False)
                        If namelist = "" Then
                            ' check to see if there's hidden active members
                            If Me.GetTeamMemberNames(rsTeamIndex, True, False) = "" Then
                                If rsTeamIndex.ToString = "" Then
                                    Response_WriteLine("<font color=""red"">Message has no Team assigned!</font>")
                                Else
                                    Response_WriteLine("<br><font color=""red"">Team has no active Members</font>")
                                End If
                            Else
                                Response_WriteLine("<br><font color=""orange"">Team has hidden Members only</font>")
                            End If
                        Else
                            Response.Write(" - " & namelist)
                        End If
                        If Me.IsTeamActive(rsTeamIndex) = "No" Then
                            Response_WriteLine("<br><font color=""red"">Team is no longer active. ")
                            If rsCompleted = "Yes" Then
                                ' nothing...
                            Else
                                Response_WriteLine("Transfer this ticket to another Team.")
                            End If
                            Response_WriteLine("</font>")
                        End If
                        Response_WriteLine("</td></tr>")
                        Response_WriteLine("<tr><td>Location:</td><td>" & caLocationName & "</td></tr>")
                        Response_WriteLine("<tr><td>Site:</td><td>" & rsSiteNum & "&nbsp;" & Me.GetSiteName(rsSiteNum) & "</td></tr>")
                        Response_WriteLine("<tr><td nowrap>Email Sent:</td><td>" & rsEmailSent & "</td></tr>")
                        Response_WriteLine("<tr><td valign=""top"">Index:</td><td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & """>" & I & "</a></td></tr>")
                        ' only show Flag choice if they exist for this Reason
                        sSqlString = "SELECT COUNT(tab_Flags.Fl_Type) AS THECOUNT FROM tab_Flags WHERE tab_Flags.Fl_Type = '" & RType & "';"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader
                            If sqlDataReader.Read = True Then
                                If sqlDataReader.Item("THECOUNT") = 0 Then
                                    ' no Flags defined for this Type
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td valign=""top"" nowrap>Flag for Review?</td>")
                                    Response_WriteLine("<td valign=""top"">No automated escalation procedure exists for this <i>Message Type</i><br>")
                                    Response_WriteLine("You'll need to verbally communicate escalation information about this message.</td>")
                                    Response_WriteLine("</tr>")
                                Else
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td nowrap>Flag for Review?</td>")
                                    Response_WriteLine("<td valign=""top""><a class=""submitAsLink"" href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&flag=Yes"" target=""_blank"">Flag</a> <small><font color=""green"">Click to open the escalation options in a new window</font></small>")
                                    Response_WriteLine("</td></tr>")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        Select Case RType
                            Case "FEE"
                                ' Vendor reasons will show Patient fields as editable
                                ' Patient reasons will show vendor reasons as editable
                                If rsVendorName <> "" Then
                                    Response_WriteLine("<tr valign=""top"">")
                                    Response_WriteLine("<td nowrap>Clone Vendor?</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<form name=""frmMessageCloneFromViewingFEEVendor"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:0;margin-bottom:0;float:left"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Clone"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & rsSiteNum & """>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & rsLocationIndex & """>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & rsTeamIndex & """>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & RType & """>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_MessageIndex"" value=""" & I & """>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_CloneType"" value=""Vendor"">")
                                    Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmMessageCloneFromViewingFEEVendor.submit()"">Clone</a>  ")
                                    Response_WriteLine("<small><font color=""green"">Clone the Vendor info to <i>Open a New Message</i> with new Patient information.</font></small>")
                                    Response_WriteLine("</form>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                End If
                                Response_WriteLine("<tr valign=""top"">")
                                Response_WriteLine("<td nowrap>Clone Patient?</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<form name=""frmMessageCloneFromViewingFEEPatient"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:0;margin-bottom:0;float:left"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Clone"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & rsSiteNum & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & rsLocationIndex & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & rsTeamIndex & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & RType & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_MessageIndex"" value=""" & I & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_CloneType"" value=""Patient"">")
                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmMessageCloneFromViewingFEEPatient.submit()"">Clone</a>  ")
                                Response_WriteLine("<small><font color=""green"">Clone the Patient info to <i>Open a New Message</i> with new Vendor information.</font></small>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</td>")
                                Response_WriteLine("</tr>")
                            Case "PACT"
                                Response_WriteLine("<tr valign=""top"">")
                                Response_WriteLine("<td nowrap>Clone Message?</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<form name=""frmMessageCloneFromViewingPACT"" method=""POST"" action=""" & _clsMessageVAR.WebURL & """ style=""margin-top:0;margin-bottom:0;float:left"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_submit"" value=""Yes"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Phase"" value=""Clone"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & rsSiteNum & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & rsLocationIndex & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & rsTeamIndex & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_MessageType"" value=""" & RType & """>")
                                Response_WriteLine("<input type=""hidden"" name=""form_MessageIndex"" value=""" & I & """>")
                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmMessageCloneFromViewingPACT.submit()"">Clone</a> <small><font color=""green"">Clone the Patient info to <i>Open a New Message</i>.</font></small>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</td>")
                                Response_WriteLine("</tr>")
                            Case Else
                                ' no other clone type exists... yet
                        End Select

                        ' provide average completion time in hours for this team for this reason
                        ' function ShowAverage(rsTeamIndex, rsReason)
                        ' returns "" if server was too busy in last 30 minutes to run this query
                        MSGdelay = Me.ShowAverage(rsTeamIndex, rsReason)
                        If MSGdelay <> "" Then
                            Response_WriteLine("<tr valign=""top"">")
                            Response_WriteLine("<td>Average Delay:</td>")
                            Response_WriteLine("<td>" & MSGdelay & "</td>")
                            Response_WriteLine("</tr>")
                        End If

                        ' All sorts have final sort by AuditDate DESC, AuditTime DESC
                        ' Thus the newest status update will generate the age.
                        ' generate Age for [Assignment, Transfer, Flag, Status Update]
                        ' show the audit history associated with THIS Message:
                        If rsCompleted = "Yes" Then
                            ' show message Processing Time from creation to closure in the Audit instead
                        Else
                            sSqlString = "SELECT TOP 1 tab_Audit.Au_Action, tab_Audit.Au_Dt, tab_Audit.Au_Tm" & " FROM tab_Audit WHERE tab_Audit.Au_IndexMessage = " & I & " AND tab_Audit.Au_Action <> 'Viewed'" & " ORDER BY tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If sqlDataReader.Read = False Then
                                    Response_WriteLine("<tr valign=""top""><td>Message Age:</td><td>No actions since message creation.</td></tr>")
                                Else
                                    ' newest Action, generate the delay between Audit and Now
                                    'strAge = roundClock(ComputeDelay(sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), Date, Time, "BH"))
                                    strAge = Me.ComputeDelay(sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), theDate, DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), "BH")
                                    If strAge < 8.001 Then
                                        ' up to 1 business day in age is good
                                        sAge = "<font color=""green"">" & Me.roundClock(strAge) & "</font>"
                                    Else
                                        If strAge < 16.001 Then
                                            ' up to 2 business days in age is a warning
                                            sAge = "<font color=""orange"">" & Me.roundClock(strAge) & "</font>"
                                        Else
                                            ' over 2 business days in age is bad
                                            sAge = "<font color=""red"">" & Me.roundClock(strAge) & "</font>"
                                        End If
                                    End If
                                    Response_WriteLine("<tr valign=""top"">")
                                    Response_WriteLine("<td>Message Age:</td>")
                                    Response_WriteLine("<td>" & sAge & " time elapsed (business hours) since last message action (" & sqlDataReader.Item("Au_Action") & ").</td>")
                                    Response_WriteLine("</tr>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                        End If
                        Response_WriteLine("</table>")
                        Response_WriteLine("</td></tr></table></div></div>")
                        Response_WriteLine("</p>")
                        Response_WriteLine("<script language=""javascript"">")
                        Response_WriteLine("	function Validate() {")
                        Response_WriteLine("		// prevents double clicking the submit button to submit it twice")
                        Response_WriteLine("		document.frm_MSG_ACTIONS.idSubmitUpdate.disabled = true;")
                        Response_WriteLine("		return true;")
                        Response_WriteLine("	}")
                        Response_WriteLine("</script>")
                        ' AUDIT DISPLAY
                        ' show the audit message if it existed
                        If auditMSG <> "" Then
                            Response.Write(auditMSG)
                        End If

                        ' show the audit history associated with THIS Message:
                        sSqlString = "SELECT tab_Audit.Au_IndexMessage, tab_Audit.Au_Action, tab_Audit.Au_Detail, tab_Audit.Au_Dt, tab_Audit.Au_Tm, tab_Audit.Au_Username" & " FROM tab_Audit WHERE tab_Audit.Au_IndexMessage = " & I & " ORDER BY tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"

                        Dim SaveAuditCloseDt, SaveAuditCloseTm
                        SaveAuditCloseDt = ""
                        SaveAuditCloseTm = ""

                        'On Error Resume Next

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Err.Number <> 0 Then
                                Response.Write("<p>A server error occurred. Unable to load the Audit History for this message at this time, try again later.</p>")
                                Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                'On Error GoTo 0
                            Else
                                'On Error GoTo 0
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellspacing=""0"" cellpadding=""0""><tr><td>")
                                Response_WriteLine("<table>")
                                Response_WriteLine("<tr><th colspan=""4"">Audit History</th></tr>")
                                Response_WriteLine("<tr><th>Date</th><th>Time</th><th>Action</th><th>User</th></tr>")
                                cntr = 0
                                While sqlDataReader.Read = True
                                    ' sSqlString nVarChar(MAX) fields are mysteriously Nothing unless they are referenced in the order they are returned
                                    MAction = sqlDataReader.Item("Au_Action")
                                    MDetail = sqlDataReader.Item("Au_Detail")
                                    MDt = sqlDataReader.Item("Au_Dt")
                                    MTm = sqlDataReader.Item("Au_Tm")
                                    MUsername = sqlDataReader.Item("Au_Username")
                                    If IsDBNull(MDt) Then
                                        MDt = ""
                                    End If
                                    If IsDBNull(MTm) Then
                                        MTm = Nothing
                                    End If
                                    If IsDBNull(MAction) Then
                                        MAction = ""
                                    Else
                                        If MAction = "Completed" Then
                                            SaveAuditCloseDt = MDt
                                            SaveAuditCloseTm = MTm
                                        End If
                                    End If
                                    If IsDBNull(MUsername) Then
                                        MUsername = ""
                                    End If
                                    If IsDBNull(MDetail) Then
                                        MDetail = ""
                                    End If
                                    If cntr Mod 2 = 0 Then
                                        Response_WriteLine("<tr bgcolor=""#ffffff"">")
                                    Else
                                        Response_WriteLine("<tr bgcolor=""whitesmoke"">")
                                    End If
                                    Response_WriteLine("<td align=""right"">")
                                    If IsDBNull(MDt) Then
                                        Response_WriteLine("&nbsp;")
                                    Else
                                        Response_WriteLine("" & MDt & "")
                                    End If
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    If MTm Is Nothing Then
                                        Response_WriteLine("&nbsp;")
                                    Else
                                        Response_WriteLine("" & Me.formatTime(MTm, False) & "")
                                    End If
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    If MAction = "" Then
                                        Response_WriteLine("&nbsp;")
                                    Else
                                        Response_WriteLine("" & MAction & "")
                                    End If
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    If MUsername = "" Then
                                        Response_WriteLine("&nbsp;")
                                    Else
                                        'Response_WriteLine("" & Me.CleanUserName(MUsername) & "")
                                        Response_WriteLine("" & Me.CleanUserName(MUsername) & " - " & PollMemberNameForLogin(MUsername) & "")
                                    End If
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    If MDetail <> "" Then
                                        ' show Detail on own row:
                                        If cntr Mod 2 = 0 Then
                                            Response_WriteLine("<tr bgcolor=""#ffffff"">")
                                        Else
                                            Response_WriteLine("<tr bgcolor=""whitesmoke"">")
                                        End If
                                        Response_WriteLine("<td>&nbsp;</td>")
                                        Response_WriteLine("<td>&nbsp;</td>")
                                        Response_WriteLine("<td colspan=""2"" align=""left"">" & Replace(MDetail, vbCrLf, "<br>") & "</td>")
                                        Response_WriteLine("</tr>")
                                    End If
                                    cntr = cntr + 1
                                End While
                                If cntr Mod 2 = 0 Then
                                    Response_WriteLine("<tr bgcolor=""#ffffff"">")
                                Else
                                    Response_WriteLine("<tr bgcolor=""whitesmoke"">")
                                End If
                                Response_WriteLine("<td align=""right"">" & rsDt & "</td><td align=""right"">" & Me.formatTime(rsTm, False) & "</td><td>Created</td><td>" & Me.CleanUserName(rsUsername) & " - " & PollMemberNameForLogin(rsUsername) & "</td></tr>")
                                If SaveAuditCloseDt.ToString <> "" And SaveAuditCloseTm.ToString <> "" Then
                                    Response_WriteLine("<tr valign=""top""><td colspan=""2"" align=""right"">Processing Time:</td><td>")
                                    strAge = Me.ComputeDelay(rsDt, rsTm, SaveAuditCloseDt, SaveAuditCloseTm, "BH")
                                    If strAge < 8.001 Then
                                        ' up to 1 business day in age is good
                                        Response_WriteLine("<font color=""green"">" & Me.roundClock(strAge) & "</font>")
                                    Else
                                        If strAge < 16.001 Then
                                            ' up to 2 business days in age is a warning
                                            Response_WriteLine("<font color=""orange"">" & Me.roundClock(strAge) & "</font>")
                                        Else
                                            ' over 2 business days in age is bad
                                            Response_WriteLine("<font color=""red"">" & Me.roundClock(strAge) & "</font>")
                                        End If
                                    End If
                                    Response_WriteLine("Work Hours (8a-5p)<br>")
                                    strAge = Me.ComputeDelay(rsDt, rsTm, SaveAuditCloseDt, SaveAuditCloseTm, "Weekdays")
                                    If strAge < 1.001 Then
                                        ' up to 1 business day in age is good
                                        Response_WriteLine("<font color=""green"">" & Me.roundit(strAge, 1) & "</font>")
                                    Else
                                        If strAge < 2.001 Then
                                            ' up to 2 business days in age is a warning
                                            Response_WriteLine("<font color=""orange"">" & Me.roundit(strAge, 1) & "</font>")
                                        Else
                                            ' over 2 business days in age is bad
                                            Response_WriteLine("<font color=""red"">" & Me.roundit(strAge, 1) & "</font>")
                                        End If
                                    End If
                                    Response_WriteLine("Work Days")
                                    Response_WriteLine("</td></tr>")
                                End If
                                Response_WriteLine("</table>")
                                Response_WriteLine("</td></tr></table>")
                            End If  ' err.number <> 0

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Else
                        Response_WriteLine("<p>No access to this " & Me.GetLocationName(rsLocationIndex) & " Message.</p>")
                    End If

                End If ' QSflag = "Yes"
                ' DISPLAY END

            Else
                Response_WriteLine("<p>Index " & I & " not found.</p>")
            End If

        Else
            ' No Index "I" chosen, so give a list of I's to choose from
            Dim ctr, lastIndex, color, row
            Dim FullID
            Dim Max, Start, Finish
            Dim prevFinish, nextStart

            Select Case menu

                Case "Admin"
                    ' Audit, History, Reports
                    Response_WriteLine("<p>Choose one of the Admin Menu items</p>")
                Case "Open"
                    ' View Active Messages
                    ' ---
                    ' view Site - Active Messages
                    ' ---

                    ' limit to open Messages - otherwise the DO WHILE loop gets long
                    Dim counterMSG, bUpdateFound, bShowAllWhite

                    ' sSqlString View exists for sSqlString Management Studio reference:
                    ' named "View_AllOpen" that has JOINS defined in the View
                    'SELECT     dbo.tab_Messages.Msg_Index, dbo.tab_Messages.Msg_Assigned, dbo.tab_Messages.Msg_Completed, dbo.tab_Teams.Te_Name, dbo.tab_Locations.Lo_Name, 
                    'dbo.tab_Members.Me_Name, dbo.tab_Members.Me_Title, dbo.tab_Messages.Msg_LastName, dbo.tab_Messages.Msg_LastFour, 
                    'dbo.tab_Messages.Msg_ReturnCall, dbo.tab_Messages.Msg_Reason, dbo.tab_Messages.Msg_VendorName, dbo.tab_Messages.Msg_Dt, 
                    'dbo.tab_Messages.Msg_Tm, dbo.tab_Audit.Au_Action, dbo.tab_Audit.Au_Dt, dbo.tab_Audit.Au_Tm, dbo.tab_Messages.Msg_SiteNum
                    'FROM         dbo.tab_Messages LEFT OUTER JOIN
                    'dbo.tab_Audit ON dbo.tab_Messages.Msg_Index = dbo.tab_Audit.Au_IndexMessage LEFT OUTER JOIN
                    ' I Question the validity of thus "AND" in the Members join
                    ' it doesn't use LIKE it uses =.  originally usernames where mixed case
                    'dbo.tab_Members ON dbo.tab_Messages.Msg_Assigned = dbo.tab_Members.Me_Username AND 
                    'dbo.tab_Messages.Msg_TeamIndex = dbo.tab_Members.Me_TeamIndex LEFT OUTER JOIN
                    'dbo.tab_Teams ON dbo.tab_Messages.Msg_TeamIndex = dbo.tab_Teams.Te_Index LEFT OUTER JOIN
                    'dbo.tab_Locations ON dbo.tab_Messages.Msg_LocationIndex = dbo.tab_Locations.Lo_Index
                    'WHERE     (dbo.tab_Messages.Msg_Completed IS NULL)

                    sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Assigned, tab_Messages.Msg_TeamIndex," & " tab_Locations.Lo_Name, tab_Teams.Te_Name," & " tab_Messages.Msg_ReturnCall, tab_Messages.Msg_Reason, tab_Messages.Msg_FirstName, tab_Messages.Msg_LastName, tab_Messages.Msg_LastFour, tab_Messages.Msg_DOB," & " tab_Messages.Msg_VendorName, tab_Messages.Msg_Dt, tab_Messages.Msg_Tm," & " tab_Audit.Au_Action, tab_Audit.Au_Dt, tab_Audit.Au_Tm"

                    If action = "My" Or action = "Team" Then

                        ' "My"
                        ' --- means filter by tab_Messages.Msg_Assigned
                        ' "My" queries take 20x as long with Username in the WHERE clause.  
                        ' this method used a WHERE clause to filter by Assigned to Member - regardless of the Team or site!
                        ' however NOT doing this anymore:   " AND tab_Messages.Msg_Assigned LIKE '" & UCase(UserName) & "'"
                        '
                        ' It is NOT possible for a message to be assigned to a member without that member being part of a team.
                        ' Therefore treat My as Team and then filter in the "do while" loop instead.

                        ' Team Messages - all teams for this member
                        ' Assigned to anybody or nobody
                        If Me.AdminTeam = -1 Or Me.AdminTeam = 0 Then
                            ' =-1 (multiple Teams)
                            ' ="0" (System/Site Admin but also 1 or more teams)
                            ' --- means filter with a right join to get all (active or inactive) Teams this member is part of
                            sSqlString = sSqlString & " FROM (((tab_Messages RIGHT JOIN tab_Members ON tab_Messages.Msg_TeamIndex = tab_Members.Me_TeamIndex)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_Completed IS NULL" & " AND tab_Members.Me_Username LIKE '" & UCase(Me.UserName) & "'"

                            ' the RIGHT JOIN and matching username accounts for "IN (n1,n2,n3)" situation:
                            '	where (tab_Messages.Msg_TeamIndex = n1
                            '	or tab_Messages.Msg_TeamIndex = n2
                            '	...
                            '	or tab_Messages.Msg_TeamIndex = n4)
                        Else
                            ' <> -1 then
                            ' single Team for this member
                            ' --- means filter with AdminTeam global to limit to just this one team
                            sSqlString = sSqlString & " FROM ((tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_Completed IS NULL" & " AND tab_Messages.Msg_TeamIndex = " & Me.AdminTeam
                        End If

                        ' the RIGHT JOIN introduces some NULL Msg_Index values, when there are no non-completed messages for that team.
                        ' so get rid of those rows
                        sSqlString = sSqlString & " AND tab_Messages.Msg_Index IS NOT NULL"

                        ' These make for a slower query due to more WHERE clauses
                        ' no need to filter Lo_Type for "My" or "Team"
                        ' no need to filter Me_SiteNum when the TeamIndex is used.

                    Else

                        ' default to "All" Messages for this site
                        ' --- means don't filter by team or member  Me.UserName 
                        sSqlString = sSqlString & " FROM ((tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_Completed IS NULL"
                        ' this statement does not improve speed:
                        ' attempt would be to not pull audit records that didn't matter in calculating age
                        ' it assumes all records have a Viewed
                        ' but if a message didn't have a "Viewed" but was "Transferred", it wouldn't ever be shown
                        'sSqlString = sSqlString & " AND (tab_Audit.Au_Action = 'Status Updated' OR tab_Audit.Au_Action = 'Viewed' OR tab_Audit.Au_Action IS NULL)"
                        If Me.AdminType = "All" And S = "" Then
                            sSqlString = sSqlString & " And tab_Messages.Msg_SiteNum IN(" & Me.AdminSites & ")"
                        Else
                            If S = "" Then
                                ' no Site limitation
                            Else
                                sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "'"
                            End If
                        End If
                        If Me.AdminType <> "All" Then
                            ' filter Lo_Type for "All"
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If

                    End If ' action = "My" or "Team"


                    ' all are sorted by Au_Dt DESC, Au_TM DESC in order to place the most recent Au_Action="Status Update" at the top
                    Select Case sort
                        Case "IndexD"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "IndexA"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm ASC;"
                        Case "ProcessA"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Assigned, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "ProcessD"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Assigned DESC, tab_Messages.Msg_Index ASC, tab_Audit.Au_Dt ASC, tab_Audit.Au_Tm ASC;"
                        Case "LocationA"
                            ' before joins this was the best it could do
                            'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LocationIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "LocationD"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum DESC, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "TeamA"
                            ' before joins this was the best it could do
                            'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "TeamD"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "Reason"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Reason, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "Return"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_ReturnCall DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "LastNameA"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "LastNameD"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "LastFourA"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastFour, tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "LastFourD"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastFour DESC, tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "VendorName"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_VendorName, tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case "CrDt"
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Dt DESC, tab_Messages.Msg_Tm DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                        Case Else
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt DESC, tab_Audit.Au_Tm DESC;"
                    End Select

                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString.OPEN.=" & sSqlString & "<br>")
                    End If
                    ' default timeout is 30
                    ' don't need to increase it now that the lookup queries are optimized 
                    ' db.CommandTimeout = 45 TODO - Bumped to 45 seconds 11/1/17
                    'On Error Resume Next
                    MyCommand.CommandTimeout = 45
                    'MyCommand.CommandText = "waitfor delay '00:00:50';"
                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Err.Number <> 0 Then
                            Response.Write("<p>A server error occurred. Unable to load the Open Messages at this time, try again later.</p>")
                            Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                            'On Error GoTo 0
                        Else
                            'On Error GoTo 0
                            If sqlDataReader.HasRows = True Then
                                cntr = 0
                                ' Note that date and time are separate TD fields so they can be copied into different excel columns
                                Response_WriteLine("<p>Showing&nbsp;<b>" & action & "&nbsp;")
                                If action = "My" Then
                                    Response_WriteLine("Assigned&nbsp;")
                                End If
                                Response_WriteLine("</b>Open&nbsp;")
                                If Me.AdminType <> "All" Then
                                    Response_WriteLine("" & Me.AdminType & "&nbsp;")
                                End If
                                Response_WriteLine("Messages.</p>")
                                ' flush buffer so user sees title bars and knows the page is loading so they don't hit refresh impatiently
                                If Response.Buffer = True Then
                                    'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                                    'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                                    Response.Flush()
                                End If
                                Response_WriteLine("<div class=""container-fluid"">")
                                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #ffffff;"">")
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed""><tbody>")
                                Response_WriteLine("<tr bgcolor=""white"" valign=""bottom"">")
                                If System.Web.HttpContext.Current.Session(“Index1Sort”) = "IndexA" Then
                                    System.Web.HttpContext.Current.Session(“Index1Sort”) = "IndexD"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=IndexD"">I</a>ndex</th>")
                                Else
                                    System.Web.HttpContext.Current.Session(“Index1Sort”) = "IndexA"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=IndexA"">I</a>ndex</th>")
                                End If
                                If System.Web.HttpContext.Current.Session(“ProcessSort”) = "ProcessA" Then
                                    System.Web.HttpContext.Current.Session(“ProcessSort”) = "ProcessD"
                                    Response_WriteLine("<th bgcolor=""#d6dbe9""><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=ProcessD"">A</a>ssigned?</th>")
                                Else
                                    System.Web.HttpContext.Current.Session(“ProcessSort”) = "ProcessA"
                                    Response_WriteLine("<th bgcolor=""#d6dbe9""><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=ProcessA"">A</a>ssigned?</th>")
                                End If
                                If System.Web.HttpContext.Current.Session(“Location1Sort”) = "LocationA" Then
                                    System.Web.HttpContext.Current.Session(“Location1Sort”) = "LocationD"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationD"">L</a>ocation</th>")
                                Else
                                    System.Web.HttpContext.Current.Session(“Location1Sort”) = "LocationA"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationA"">L</a>ocation</th>")
                                End If
                                If System.Web.HttpContext.Current.Session(“Team1Sort”) = "TeamA" Then
                                    System.Web.HttpContext.Current.Session(“Team1Sort”) = "TeamD"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamD"">T</a>eam</th>")
                                Else
                                    System.Web.HttpContext.Current.Session(“Team1Sort”) = "TeamA"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamA"">T</a>eam</th>")
                                End If
                                Response_WriteLine("<th class=""visible-sm visible-md visible-lg"">First Name</th>")
                                If System.Web.HttpContext.Current.Session(“LastName1Sort”) = "LastNameA" Then
                                    System.Web.HttpContext.Current.Session(“LastName1Sort”) = "LastNameD"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameD"">L</a>ast Name</th>")
                                Else
                                    System.Web.HttpContext.Current.Session(“LastName1Sort”) = "LastNameA"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameA"">L</a>ast Name</th>")
                                End If
                                If System.Web.HttpContext.Current.Session(“LastFour1Sort”) = "LastFourA" Then
                                    System.Web.HttpContext.Current.Session(“LastFour1Sort”) = "LastFourD"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastFourD"">L</a>ast 4</th>")
                                Else
                                    System.Web.HttpContext.Current.Session(“LastFour1Sort”) = "LastFourA"
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastFourA"">L</a>ast 4</th>")
                                End If
                                If _clsMessageVAR.Gl_overrideDOB = False Then Response_WriteLine("<th class=""visible-sm visible-md visible-lg"" nowrap>DOB</th>")
                                Response_WriteLine("<th class=""visible-sm visible-md visible-lg""><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason"">R</a>eason</th>")
                                Response_WriteLine("<th class=""visible-sm visible-md visible-lg""><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Return"">R</a>eturn</th>")
                                Response_WriteLine("<th class=""visible-sm visible-md visible-lg"" nowrap><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=CrDt"">C</a>r.Dt</th>")
                                Response_WriteLine("<th class=""visible-sm visible-md visible-lg"" nowrap>Cr.Tm</th>")
                                Response_WriteLine("<th class=""visible-sm visible-md visible-lg"">Age</th>")
                                Response_WriteLine("</tr>")
                                lastIndex = 0
                                row = ""
                                bUpdateFound = False
                                '   bUpdateFound = false, newly initialized
                                '   bUpdateFound = true, status update found
                                '      true will prevent Find/Replace again if there are more status updates for same index
                                While sqlDataReader.Read = True

                                    If lastIndex <> sqlDataReader.Item("Msg_Index") Then
                                        ' new index, display the last one
                                        Response.Write(row & vbCrLf)
                                        row = ""
                                        bUpdateFound = False
                                        bShowAllWhite = False
                                    End If
                                    If Not bUpdateFound And row = "" Then
                                        ' build row with placeholder for Age: "<td id=Age>&nbsp;</td>"

                                        MAssigned = sqlDataReader.Item("Msg_Assigned")
                                        If IsDBNull(MAssigned) Then
                                            MAssigned = ""
                                        End If

                                        ' "My" filter is not done in sSqlString query, too CPU intensive in a giant database to text filter on the Assigned field
                                        ' vbscript is faster at filtering it in the result sqlDataReader.					
                                        ' StrComp(str1, str2, 1) means text comparison, ignores case. returns 0 if equal
                                        If action = "My" And StrComp(Me.UserName, MAssigned, 1) <> 0 Then
                                            ' skip this non-assigned message for the MY results
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write(MAssigned & ",")
                                            End If
                                        Else

                                            If MAssigned = "" Then
                                                AssignedName = "&nbsp;"
                                            Else
                                                ' get assignee Display Name/Title from lookup
                                                ' blank if invalid match
                                                AssignedName = Me.GetMemberNameFromUandTI(MAssigned, sqlDataReader.Item("Msg_TeamIndex"))
                                                If AssignedName = "" Then
                                                    ' since blank,  it back to the Username that is stored in tab_Messages.Msg_Assigned
                                                    ' this is due to a member's row being deleted form the Members table
                                                    ' or the username renamed w/o changing corresponding Messages
                                                    AssignedName = "<font color=""red"">" & Me.CleanUserName(MAssigned) & "</font>"
                                                End If
                                            End If

                                            ' NEW row
                                            If sqlDataReader.Item("Msg_Reason") = "Declined Telephone Triage" Or sqlDataReader.Item("Msg_Reason") = "VISN CCC Urgent Communication" Or sqlDataReader.Item("Msg_Reason") = "VISN Clinical Contact Center Triage – Now" Or sqlDataReader.Item("Msg_Reason") = "VISN Clinical Contact Center Triage – LIP Consult/Warm Handoff" Or sqlDataReader.Item("Msg_Reason") = "Pharmacist call back" Then
                                                bShowAllWhite = True
                                                row = "<tr class=""hover-item-white"" style=""background-color:red;font-weight:bold;color:#ffffff;"" valign=""top"">"
                                            ElseIf sqlDataReader.Item("Msg_Reason") = "VISN Clinical Contact Center Triage – within 4 hours" Or sqlDataReader.Item("Msg_Reason") = "Medication (expedited mail)" Or sqlDataReader.Item("Msg_Reason") = "Call Transfer" Or sqlDataReader.Item("Msg_Reason") = "GENERAL" Then
                                                bShowAllWhite = True
                                                row = "<tr class=""hover-item-black"" style=""background-color:yellow;font-weight:bold;color:#000000;"" valign=""top"">"
                                            ElseIf sqlDataReader.Item("Msg_Reason") = "VISN Clinical Contact Center Triage – within 24 hours" Or sqlDataReader.Item("Msg_Reason") = "VISN Pharmacy CCC – Window" Or sqlDataReader.Item("Msg_Reason") = "Medication (local mail)" Then
                                                bShowAllWhite = True
                                                row = "<tr class=""hover-item-white"" style=""background-color:green;font-weight:bold;color:#ffffff;"" valign=""top"">"
                                            ElseIf sqlDataReader.Item("Msg_Reason") = "Refused RN Recommendation" Then
                                                bShowAllWhite = True
                                                row = "<tr class=""hover-item-white"" style=""background-color:orange;font-weight:bold;color:#ffffff;"" valign=""top"">"
                                            ElseIf sqlDataReader.Item("Msg_Reason") = "Medication (window pickup)" Then
                                                bShowAllWhite = True
                                                row = "<tr class=""hover-item-white"" style=""background-color:#ADD8E6;font-weight:bold;color:#000000;"" valign=""top"">"
                                            ElseIf sqlDataReader.Item("Msg_Reason") = "Discharge Handoff" Then
                                                bShowAllWhite = True
                                                row = "<tr class=""hover-item-white"" style=""background-color:purple;font-weight:bold;color:#ffffff;"" valign=""top"">"
                                            Else
                                                If cntr Mod 2 = 0 Then
                                                    row = "<tr valign=""top"">"
                                                Else
                                                    row = "<tr bgcolor=""whitesmoke"" valign=""top"">"
                                                End If
                                            End If
                                            row = row & "<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>"
                                            row = row & "<td>" & AssignedName & "</td>"
                                            row = row & "<td>" & sqlDataReader.Item("Lo_Name") & "</td>"
                                            If bShowAllWhite Then
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    row = row & Me.ColorizeTeamBackgroundTD(sqlDataReader.Item("Te_Name")) & "</td>"
                                                Else
                                                    row = row & "<td>" & sqlDataReader.Item("Te_Name") & "</font></td>"
                                                End If
                                            Else
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    row = row & Me.ColorizeTeamBackgroundTD(sqlDataReader.Item("Te_Name")) & "</td>"
                                                Else
                                                    row = row & "<td>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</font></td>"
                                                End If
                                            End If
                                            row = row & "<td  class=""visible-sm visible-md visible-lg"" valign=""top"">"
                                            If IsDBNull(sqlDataReader.Item("Msg_FirstName")) Then
                                                row = row & "&nbsp;"
                                            Else
                                                row = row & sqlDataReader.Item("Msg_FirstName")
                                            End If
                                            row = row & "</td>"
                                            row = row & "<td valign=""top"">"
                                            If IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                                row = row & "&nbsp;"
                                            Else
                                                row = row & sqlDataReader.Item("Msg_LastName")
                                            End If
                                            row = row & "</td>"
                                            row = row & "<td valign=""top"">"
                                            If IsDBNull(sqlDataReader.Item("Msg_LastFour")) Then
                                                row = row & "&nbsp;"
                                            Else
                                                row = row & sqlDataReader.Item("Msg_LastFour")
                                            End If
                                            row = row & "</td>"
                                            If _clsMessageVAR.Gl_overrideDOB = False Then
                                                row = row & "<td valign=""top"">"
                                                If IsDBNull(sqlDataReader.Item("Msg_DOB")) Then
                                                    row = row & "&nbsp;"
                                                Else
                                                    row = row & sqlDataReader.Item("Msg_DOB")
                                                End If
                                                row = row & "</td>"
                                            End If
                                            row = row & "<td class=""visible-sm visible-md visible-lg"" valign=""top"">"
                                            If IsDBNull(sqlDataReader.Item("Msg_Reason")) Then
                                                row = row & "&nbsp;"
                                            Else
                                                row = row & sqlDataReader.Item("Msg_Reason")
                                            End If
                                            row = row & "</td>"
                                            If sqlDataReader.Item("Msg_ReturnCall") = "Waiting" And Not bShowAllWhite Then
                                                row = row & "<td class=""visible-sm visible-md visible-lg""><font color=""red"">" & sqlDataReader.Item("Msg_ReturnCall") & "</font></td>"
                                            Else
                                                row = row & "<td class=""visible-sm visible-md visible-lg"">" & sqlDataReader.Item("Msg_ReturnCall") & "</td>"
                                            End If
                                            row = row & "<td class=""visible-sm visible-md visible-lg"" align=""right"" nowrap>" & sqlDataReader.Item("Msg_Dt") & "</td>"
                                            row = row & "<td class=""visible-sm visible-md visible-lg"" align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "</td>"
                                            ' fill in placeholder for the Age
                                            row = row & "<td class=""visible-sm visible-md visible-lg"" id=Age>&nbsp;</td>"
                                            row = row & "</tr>"
                                            cntr = cntr + 1
                                        End If  ' "My Assigned" filter
                                    End If  ' bUpdateFound

                                    ' STATUS UPDATE AGE METHOD: ' first encounter with "Status Update" will  the Age placeholder:
                                    ' STATUS UPDATE AGE METHOD: if not bUpdateFound and sqlDataReader.Item("Au_Action") = "Status Updated" then
                                    ' All sorts have final sort by AuditDate DESC, AuditTime DESC
                                    ' Thus the newest status update will generate the age.
                                    ' generate Age for [Assignment, Transfer, Flag, Status Update]
                                    If Not bUpdateFound And Not IsDBNull(sqlDataReader.Item("Au_Action")) Then
                                        If sqlDataReader.Item("Au_Action") <> "Viewed" Then
                                            ' newest Status Updated, generate the delay between Audit and Now
                                            'strAge = roundClock(ComputeDelay(sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), Date, Time, "BH"))
                                            strAge = Me.ComputeDelay(sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), theDate, DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), "BH")
                                            If Not bShowAllWhite Then
                                                If strAge < 8.001 Then
                                                    ' up to 1 business day in age is good
                                                    sAge = "<font color=""green"">" & Me.roundClock(strAge) & "</font>"
                                                Else
                                                    If strAge < 16.001 Then
                                                        ' up to 2 business days in age is a warning
                                                        sAge = "<font color=""orange"">" & Me.roundClock(strAge) & "</font>"
                                                    Else
                                                        ' over 2 business days in age is bad
                                                        sAge = "<font color=""red"">" & Me.roundClock(strAge) & "</font>"
                                                    End If
                                                End If
                                            Else
                                                sAge = "<font color=""black"">" & Me.roundClock(strAge) & "</font>"
                                            End If
                                            row = Replace(row, "<td class=""visible-sm visible-md visible-lg"" id=Age>&nbsp;</td>", "<td class=""visible-sm visible-md visible-lg"" align=""right"">" & sAge & "</td>")
                                            bUpdateFound = True
                                        End If
                                    End If

                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write(".aLI=" & lastIndex & "<br>")
                                    End If
                                    lastIndex = sqlDataReader.Item("Msg_Index")
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write(".bLI=" & lastIndex & "<br>")
                                    End If

                                End While
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("lastIndex=" & lastIndex & "<br>")
                                End If
                                If lastIndex <> 0 Then
                                    ' display the last row that hasn't had a chance to be shown yet.
                                    Response.Write(row & vbCrLf)
                                    row = ""
                                End If

                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("cntr=" & cntr & "<br>")
                                End If

                                If Me.AdminType = "FEE" Or Me.AdminType = "All" Then
                                    counterMSG = "<tr><td colspan=""12""><center>There"
                                Else
                                    counterMSG = "<tr><td colspan=""11""><center>There"
                                End If
                                If cntr = 1 Then
                                    counterMSG = counterMSG & " is 1"
                                Else
                                    counterMSG = counterMSG & " are " & cntr
                                End If
                                counterMSG = counterMSG & " <b>Open """ & action
                                If action = "My" Then
                                    counterMSG = counterMSG & " Assigned"
                                End If
                                If Me.AdminType <> "All" Then
                                    counterMSG = counterMSG & " " & Me.AdminType
                                End If
                                counterMSG = counterMSG & " Messages""</b>.</center></td></tr>"
                                Response.Write(counterMSG)
                                Response_WriteLine("</tbody></table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p></div></div>")
                                Response_WriteLine("<p><b>Age</b> = time elapsed in Business Hours (8a-5p) since the most recent action on a message.<br>")
                                Response_WriteLine("Status Updates, Assignments, Transfers and Flags will all reset the Age counter.<br>")
                                Response_WriteLine("An Nothing Age value means no action has taken place yet since message creation.</p>")
                            Else
                                ' specified Site not found in db
                                Select Case action
                                    Case "My"
                                        If Me.SiteName = "" Then
                                            Response_WriteLine("<p>No site chosen for " & Me.ShowTitle & "&nbsp;" & Me.UserName & ".</p>")
                                        Else
                                            Response_WriteLine("<p>No Open ""My Assigned"" Messages in " & Me.SiteName & " for " & Me.ShowTitle & "&nbsp;" & Me.UserName & ".</p>")
                                        End If
                                    Case "Team"
                                        If Me.SiteName = "" Then
                                            Response_WriteLine("<p>No site chosen for " & Me.ShowTitle & "&nbsp;" & Me.UserName & ".</p>")
                                        Else
                                            Response_WriteLine("<p>No Open ""Team Messages"" in " & Me.SiteName & " for " & Me.ShowTitle & "&nbsp;" & Me.UserName & ".</p>")
                                        End If

                                    Case Else
                                        If Me.SiteName = "" Then
                                            Response_WriteLine("<p>No site chosen for " & Me.ShowTitle & "&nbsp;" & Me.UserName & "..</p>")
                                        Else
                                            Response_WriteLine("<p>No Open Messages in " & Me.SiteName & " for " & Me.ShowTitle & "&nbsp;" & Me.UserName & ".</p>")
                                        End If
                                End Select
                            End If  ' sqlDataReader
                        End If  ' err.number <> 0

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                Case "Search"
                    ' ---
                    ' Search Messages
                    ' ---
                    Response_WriteLine("<p><b><big>Search Messages</big></b></p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    Dim frmMessageIndex, frmLName, frmFName, frmLastFour, frmDOB, frmVName, frmLocationIndex, frmTeamIndex, formused, formCloser
                    Dim QString
                    Dim sSqlStringRange, sSqlString2

                    formused = Request.Form("formused")
                    blockSize = 500

                    ' initialize the form or querystring values
                    If formused = "Yes" Then
                        ' entrance from form
                        ' load the form variables 
                        frmMessageIndex = Request.Form("frmMessageIndex")
                        frmLName = Request.Form("frmLName")
                        frmFName = Request.Form("frmFName")
                        frmLastFour = Request.Form("frmLastFour")
                        frmDOB = Request.Form("frmDOB")
                        frmVName = Request.Form("frmVName")
                        frmLocationIndex = Request.Form("frmLocationIndex")
                        frmTeamIndex = Request.Form("frmTeamIndex")
                    Else
                        ' either initial entrance or chose sort
                        ' pass the QueryString values back to the frm fields
                        frmMessageIndex = ""
                        If (Not Request.QueryString("SLN") Is Nothing) Then frmLName = Request.QueryString("SLN").ToString() Else frmLName = ""
                        If (Not Request.QueryString("SFN") Is Nothing) Then frmFName = Request.QueryString("SFN").ToString() Else frmFName = ""
                        If (Not Request.QueryString("SLF") Is Nothing) Then frmLastFour = Request.QueryString("SLF").ToString() Else frmLastFour = ""
                        If (Not Request.QueryString("SVN") Is Nothing) Then frmVName = Request.QueryString("SVN").ToString() Else frmVName = ""
                        If (Not Request.QueryString("SLI") Is Nothing) Then frmLocationIndex = Request.QueryString("SLI").ToString() Else frmLocationIndex = ""
                        If (Not Request.QueryString("STI") Is Nothing) Then frmTeamIndex = Request.QueryString("STI").ToString() Else frmTeamIndex = ""
                    End If

                    ' create the querystring line in case sort column headers are clicked
                    If IsNumeric(frmMessageIndex) And frmMessageIndex <> "" Then
                        ' when Index chosen, ignore any other form value
                        QString = ""
                        ' also wipe the other form values so the aren't on the FORM lines, confuses users that the search may have used them
                        frmLName = ""
                        frmFName = ""
                        frmLastFour = ""
                        frmDOB = ""
                        frmVName = ""
                        frmLocationIndex = ""
                        frmTeamIndex = ""
                    Else
                        QString = "&SLN=" & frmLName & "&SFN=" & frmFName & "&SLF=" & frmLastFour & "&SVN=" & frmVName & "&SLI=" & frmLocationIndex & "&STI=" & frmTeamIndex
                    End If

                    If S = "" Then
                        LocationSelect = ""
                        TeamSelect = ""
                        'LocationSelect = "<select name=""frmLocationIndex"" class=""form-control""><option></option></select>"
                        'TeamSelect = "<select name=""frmTeamIndex"" class=""form-control""><option></option></select>"
                    Else
                        If Me.AdminType = "All" Then
                            sSqlString = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & S & "' AND tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SortOrder;"
                        Else
                            sSqlString = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & S & "' AND tab_Locations.Lo_Type = '" & Me.AdminType & "' AND tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SortOrder;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                LocationSelect = ""
                            Else
                                LocationSelect = "<select name=""frmLocationIndex"" class=""form-control""><option></option>" & vbCrLf
                                While sqlDataReader.Read = True
                                    If CStr(sqlDataReader.Item("Lo_Index")) = frmLocationIndex Then
                                        formCloser = """ selected>"
                                    Else
                                        formCloser = """>"
                                    End If
                                    LocationSelect = LocationSelect & "<option value=""" & sqlDataReader.Item("Lo_Index") & formCloser & sqlDataReader.Item("Lo_Name") & "</option>" & vbCrLf
                                End While
                                LocationSelect = LocationSelect & "</select>"
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name" & " FROM tab_Teams LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & S & "' AND tab_Teams.Te_Active = 'Yes'"
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                TeamSelect = ""
                            Else
                                TeamSelect = "<select name=""frmTeamIndex"" class=""form-control""><option></option>" & vbCrLf
                                While sqlDataReader.Read = True
                                    If CStr(sqlDataReader.Item("Te_Index")) = frmTeamIndex Then
                                        formCloser = """ selected>"
                                    Else
                                        formCloser = """>"
                                    End If
                                    namelist = Me.GetTeamMemberNames(sqlDataReader.Item("Te_Index"), False, False)
                                    If namelist = "" Then
                                        TeamSelect = TeamSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & formCloser & sqlDataReader.Item("Lo_SiteNum") & " - " & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & "</option>" & vbCrLf
                                    Else
                                        If Len(namelist) > 60 Then
                                            namelist = Left(namelist, 60) & "..."
                                        End If
                                        TeamSelect = TeamSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & formCloser & sqlDataReader.Item("Lo_SiteNum") & " - " & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & " - " & namelist & "</option>" & vbCrLf
                                    End If
                                End While
                                TeamSelect = TeamSelect & "</select>"
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If
                    Response_WriteLine("<form name=""frmSearch"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&action=" & action & "&sort=" & sort & """ method=""POST"">")
                    Response_WriteLine("<input type=""hidden"" name=""formused"" value=""Yes"">")
                    Response_WriteLine("<div class=""container-fluid"">")
                    Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                    Response_WriteLine("<table>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><b>Enter Message Index:</b></td></tr>")
                    Response_WriteLine("<tr><td>Index</td><td><input type=""text"" name=""frmMessageIndex"" class=""form-control"" value=""" & frmMessageIndex & """ size=""10""><BR></td></tr>		")
                    If Me.SiteName = "" Then
                        Response_WriteLine("<tr><td colspan=""2""><b>Choose a Site in order to Search Messages.</b>")
                        Response_WriteLine("<input type=""hidden"" name=""frmLName"" value="""">")
                        Response_WriteLine("<input type=""hidden"" name=""frmFName"" value="""">")
                        Response_WriteLine("<input type=""hidden"" name=""frmLastFour"" value="""">")
                        Response_WriteLine("<input type=""hidden"" name=""frmDOB"" value="""">")
                        Response_WriteLine("<input type=""hidden"" name=""frmVName"" value="""">")
                        Response_WriteLine("<input type=""hidden"" name=""frmLocationIndex"" value="""">")
                        Response_WriteLine("<input type=""hidden"" name=""frmTeamIndex"" value="""">")
                        Response_WriteLine("</td></tr>")
                        Response_WriteLine("<tr><td colspan=""2"" align=""center""><BR><input type=""Submit"" name=""Submit"" class=""btn btn-primary"" value=""Get Message Index""></td></tr>")
                    Else
                        Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""2""><b>Or enter 1 or more partial search terms:</b></td></tr>")
                        Response_WriteLine("<tr><td>Last Name</td><td><input type=""text"" name=""frmLName"" class=""form-control"" value=""" & Replace(frmLName, """", "&#34;") & """></td></tr>")
                        Response_WriteLine("<tr><td>First Name</td><td><input type=""text"" name=""frmFName"" class=""form-control"" value=""" & Replace(frmFName, """", "&#34;") & """></td></tr>")
                        Response_WriteLine("<tr><td>Last 4</td><td><input type=""text"" name=""frmLastFour"" class=""form-control"" value=""" & Replace(frmLastFour, """", "&#34;") & """></td></tr>")
                        If _clsMessageVAR.Gl_overrideDOB = False Then
                            Response_WriteLine("<tr><td>Date of Birth</td><td><input type=""date"" name=""frmDOB"" class=""form-control"" style=""width:30%;"" value=""" & Replace(frmDOB, """", "&#34;") & """></td></tr>")
                        End If
                        If Me.AdminType = "All" Or Me.AdminType = "FEE" Then
                            Response_WriteLine("<tr><td>Vendor Name &nbsp;</td><td><input type=""text"" name=""frmVName"" class=""form-control"" value=""" & Replace(frmVName, """", "&#34;") & """></td></tr>")
                        End If
                        If LocationSelect = "" Then
                            Response_WriteLine("<input type=""hidden"" name=""frmLocationIndex"" value="""">")
                        Else
                            Response_WriteLine("<tr><td>Location</td><td>" & LocationSelect & "</td></tr>")
                        End If
                        If TeamSelect = "" Then
                            Response_WriteLine("<input type=""hidden"" name=""frmTeamIndex"" value="""">")
                        Else
                            Response_WriteLine("<tr><td>Team</td><td>" & TeamSelect & "</td></tr>")
                        End If
                        Response_WriteLine("<tr><td colspan=""2"" align=""center""><BR><input type=""Submit"" name=""Submit"" class=""btn btn-primary"" value=""Search Messages""></td></tr>")
                    End If
                    Response_WriteLine("</table>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</div>")
                    Response_WriteLine("</form>")
                    If formused = "Yes" Or sort <> "" Then

                        If frmMessageIndex = "" And frmLName = "" And frmFName = "" And frmLastFour = "" And frmDOB = "" And frmVName = "" And frmLocationIndex = "" And frmTeamIndex = "" Then
                            ' Nothing entered
                            Response_WriteLine("<p>Nothing entered, try again.</p>")
                        Else
                            If IsNumeric(frmMessageIndex) Then
                                sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Assigned, tab_Messages.Msg_Reason," & " tab_Messages.Msg_LastName, tab_Messages.Msg_FirstName, tab_Messages.Msg_LastFour, tab_Messages.Msg_DOB, tab_Messages.Msg_VendorName," & " tab_Messages.Msg_TeamIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm" & " FROM (tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index" & " WHERE tab_Messages.Msg_Index = " & frmMessageIndex
                                If Me.AdminType <> "All" Then
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                                If Me.AdminSite = "000" Then
                                    ' allow all Sites
                                    sSqlString = sSqlString & ";"
                                Else
                                    ' filter to only this site
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "';"
                                End If
                            Else
                                sSqlString = "SELECT TOP " & blockSize & " tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Assigned, tab_Messages.Msg_Reason," & " tab_Messages.Msg_LastName, tab_Messages.Msg_FirstName, tab_Messages.Msg_LastFour, tab_Messages.Msg_DOB, tab_Messages.Msg_VendorName, tab_Messages.Msg_TeamIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm" & " FROM (tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index"

                                If frmLocationIndex = "" Then
                                    ' Location field not used, limit to the Selected Site
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'"
                                Else
                                    ' allow to choose any Location even if on a selected site
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_LocationIndex = " & frmLocationIndex
                                End If
                                If Me.AdminType <> "All" Then
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If

                                If frmLName = "" Then
                                    ' field not used
                                Else
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_LastName LIKE '%" & Replace(frmLName, "'", "''") & "%'"
                                End If
                                If frmFName = "" Then
                                    ' field not used
                                Else
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_FirstName LIKE '%" & Replace(frmFName, "'", "''") & "%'"
                                End If
                                If frmLastFour = "" Then
                                    ' field not used
                                Else
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_LastFour = '" & Replace(frmLastFour, "'", "''") & "'"
                                End If
                                If frmDOB = "" Then
                                    ' field not used
                                Else
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_DOB = '" & Replace(frmDOB, "'", "''") & "'"
                                End If
                                If frmVName = "" Then
                                    ' field not used
                                Else
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_VendorName LIKE '%" & Replace(frmVName, "'", "''") & "%'"
                                End If
                                If frmTeamIndex = "" Then
                                    ' field not used
                                Else
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_TeamIndex = " & frmTeamIndex
                                End If

                                ' -=-=-=-=-=-=-=-=-=- BEGIN FILTERING TO GROUPS of "blockSize"
                                ' filter sSqlString results by Start if it was chosen
                                ' as the search can have very few records per groups of 500, can't just go by Finish = Start - 499
                                ' must return TOP 500 instead, so just filter by Start	
                                ' example, Max=1000, start=992, finish=262 
                                '   (because the first 8 records aren't in this search group.)
                                '   (because 500 records meeting the search criteria spans more that 500 index values)
                                If (Not Request.QueryString("Max") Is Nothing) Then Max = Request.QueryString("Max").ToString() Else Max = ""

                                ' if navigating,
                                '   prevFinish is passed through QS to Finish
                                '   nextStart is passed through QS to Start
                                If (Not Request.QueryString("Finish") Is Nothing) Then Finish = Request.QueryString("Finish").ToString() Else Finish = ""
                                If (Not Request.QueryString("Start") Is Nothing) Then Start = Request.QueryString("Start").ToString() Else Start = ""

                                ' if navigating, 
                                '   Finish is passed through QS to nextStart
                                '   Start is passed through QS to prevFinish
                                If (Not Request.QueryString("nextStart") Is Nothing) Then nextStart = Request.QueryString("nextStart").ToString() Else nextStart = ""
                                If (Not Request.QueryString("prevFinish") Is Nothing) Then prevFinish = Request.QueryString("prevFinish").ToString() Else prevFinish = ""

                                ' at this point not all have values, depending on entry method
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("Max=" & Max & "<br>")
                                    Response.Write("Start=" & Start & "<br>")
                                    Response.Write("Finish=" & Finish & "<br>")
                                    Response.Write("nextStart=" & nextStart & "<br>")
                                    Response.Write("prevFinish=" & prevFinish & "<br>")
                                    Response.Write("sSqlString.for.derived.table.ranges=" & sSqlString & "<br><br>")
                                End If

                                ' Max
                                '   = the database's highest index, no matter what the range
                                ' get Max for undetermined start range
                                ' need to ORDER BY in the inner sSqlString statement as it includes a LIMIT "blockSize"
                                ' Min
                                '   = 0 always... that was easy :)
                                If Max.ToString = "" Then
                                    ' LIMIT 1 gives the same result as without it, but adds an additional SORT slowdown
                                    ' using MAX as it's sorted high to low
                                    ' sSqlStringRange = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM (" & sSqlString & " ORDER BY tab_Messages.Msg_Index DESC LIMIT 1);"
                                    sSqlStringRange = "SELECT MAX(tab_derived_Msg.Msg_Index) AS MAXINDEX FROM (" & sSqlString & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("Max:sSqlStringRange=" & sSqlStringRange & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlStringRange

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = True Then
                                            If Not IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                                Max = sqlDataReader.Item("MAXINDEX")
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    ' when no hits on search query, max will still be NULL so  Max to the highest index.
                                    If Max.ToString = "" Then
                                        sSqlString2 = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM tab_Messages;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("Max:sSqlString2=" & sSqlString2 & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlString2

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If sqlDataReader.Read = True Then
                                                If Not IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                                    Max = sqlDataReader.Item("MAXINDEX")
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    End If
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("Max=" & Max & "<br>")
                                End If

                                ' Start
                                '   = by default is the highest index
                                ' need to ORDER BY in the inner sSqlString statement as it includes a LIMIT "blockSize"
                                If Start.ToString = "" Then
                                    If Finish.ToString <> "" Then
                                        ' Find the correct Start filter
                                        sSqlStringRange = "SELECT MAX(tab_derived_Msg.Msg_Index) AS MAXINDEX FROM (" & sSqlString & " AND tab_Messages.Msg_Index >= " & Finish & " ORDER BY tab_Messages.Msg_Index ASC) AS tab_derived_Msg;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("Start:sSqlStringRange=" & sSqlStringRange & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlStringRange

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If sqlDataReader.Read = True Then
                                                If Not IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                                    Start = sqlDataReader.Item("MAXINDEX")
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' Finish has a value
                                        ' Start will be the previous "blockSize"
                                    End If
                                Else
                                    ' Start chosen in Querystring.
                                    ' Finish will be the next "blockSize"
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("Start=" & Start & "<br>")
                                End If

                                ' prevFinish: previous 501 messages to get the true "Previous Finish"
                                ' when no hits on search query, start will still be NULL so  start to Max.
                                If Start.ToString = "" Or IsDBNull(Start) Then
                                    Start = Max
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("Start=Max=" & Start & "<br>")
                                    End If
                                Else
                                    If prevFinish.ToString <> "" Then
                                        ' passed in QS, skip
                                    Else
                                        sSqlStringRange = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (" & sSqlString & " AND tab_Messages.Msg_Index > " & Start & " ORDER BY tab_Messages.Msg_Index ASC) AS tab_derived_Msg;"

                                        ' for MS Access, MIN doesn't need a TOP filter (supposedly for database speed)
                                        ' sSqlString does need a TOP filter
                                        ' leave on, works fine for both
                                        ' sSqlString doesn't like the query if it has the TOP filter replaced out...
                                        '   [Microsoft][ODBC sSqlString Server Driver][sSqlString Server]
                                        '   The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, 
                                        '   and common table expressions, unless TOP or FOR XML is also specified. 
                                        'sSqlStringRange = Replace(sSqlStringRange, "TOP " & blockSize & " ", "")

                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("prevFinish:sSqlStringRange=" & sSqlStringRange & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlStringRange

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If sqlDataReader.Read = True Then
                                                If Not IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                                    prevFinish = sqlDataReader.Item("MININDEX")
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    End If
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("prevFinish=" & prevFinish & "<br>")
                                End If
                                If prevFinish.ToString = "" Then
                                    prevFinish = Max
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("prevFinish=Max=" & prevFinish & "<br>")
                                    End If
                                End If

                                ' Finish and nextStart
                                '   = the lowest index in the group of "blockSize"
                                ' need to ORDER BY in the inner sSqlString statement as it includes a LIMIT "blockSize"
                                If Finish.ToString = "" Then
                                    ' Querystring doesn't have it so preload Finish from sSqlString
                                    ' Using TOP 1 instead of MAX as it's sorted low to high
                                    If Start.ToString <> "" Then
                                        'sSqlStringRange = "SELECT TOP 1 tab_Messages.Msg_Index AS MININDEX FROM (" & sSqlString & " AND tab_Messages.Msg_Index <= " & Start & " ORDER BY tab_Messages.Msg_Index DESC) ORDER BY tab_Messages.Msg_Index ASC;"
                                        sSqlStringRange = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (" & sSqlString & " AND tab_Messages.Msg_Index <= " & Start & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"
                                    Else
                                        ' Start is Nothing so default from the highest index
                                        sSqlStringRange = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (" & sSqlString & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"
                                    End If
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("Finish:sSqlStringRange=" & sSqlStringRange & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlStringRange

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = True Then
                                            If Not IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                                Finish = sqlDataReader.Item("MININDEX")
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                Else
                                    ' Finish chosen in Querystring.
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("Finish=" & Finish & "<br>")
                                End If

                                ' nextStart: next 501 messages to get the true "Next Start"
                                ' still no value on Finish so  Finish to 0
                                If Finish.ToString = "" Then
                                    Finish = 0
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("Finish=0=" & Finish & "<br>")
                                    End If
                                Else
                                    If nextStart.ToString <> "" Then
                                        ' passed in QS, skip
                                    Else
                                        If Start.ToString <> "" Then
                                            sSqlStringRange = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (" & sSqlString & " AND tab_Messages.Msg_Index <= " & Start & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"
                                        Else
                                            sSqlStringRange = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (" & sSqlString & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"
                                        End If

                                        ' nextStart needs to be 1 beyond the Finish
                                        sSqlStringRange = Replace(sSqlStringRange, "TOP " & blockSize, "TOP " & blockSize + 1)

                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("nextStart:sSqlStringRange=" & sSqlStringRange & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlStringRange

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If sqlDataReader.Read = True Then
                                                If Not IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                                    nextStart = sqlDataReader.Item("MININDEX")
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    End If
                                End If
                                If nextStart.ToString = "" Then
                                    nextStart = 0
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("nextStart=" & nextStart & "<br>")
                                End If

                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("<br>xMax=" & Max & "<br>")
                                    Response.Write("xStart=" & Start & "<br>")
                                    Response.Write("xFinish=" & Finish & "<br>")
                                    Response.Write("xnextStart=" & nextStart & "<br>")
                                    Response.Write("xprevFinish=" & prevFinish & "<br><br>")
                                End If

                                ' filter sSqlString results by Finish
                                ' when not chosen it defaults to the highest index
                                ' Start is Nothing if searching the first time
                                If Start.ToString <> "" Then
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_Index <= " & Start
                                End If

                                ' if not filtered by Finish, then the sort will grab results from outside the ranges
                                ' finish has a guaranteed value
                                sSqlString = sSqlString & " AND tab_Messages.Msg_Index >= " & Finish
                                ' -=-=-=-=-=-=-=-=-=- END FILTERING

                                Select Case sort
                                    Case "IndexD"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"
                                    Case "IndexA"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC;"
                                    Case "Complete"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Completed, tab_Messages.Msg_Index DESC;"
                                    Case "Assigned"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Assigned, tab_Messages.Msg_Index DESC;"
                                    Case "Reason"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Reason, tab_Messages.Msg_Index DESC;"
                                    Case "LastNameA"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName, tab_Messages.Msg_FirstName, tab_Messages.Msg_Index DESC;"
                                    Case "LastNameD"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName DESC, tab_Messages.Msg_FirstName, tab_Messages.Msg_Index DESC;"
                                    Case "FirstName"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_FirstName, tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC;"
                                    Case "LastFourA"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastFour, tab_Messages.Msg_LastName, tab_Messages.Msg_FirstName, tab_Messages.Msg_Index DESC;"
                                    Case "LastFourD"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastFour DESC, tab_Messages.Msg_LastName, tab_Messages.Msg_FirstName, tab_Messages.Msg_Index DESC;"
                                    Case "VendorName"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_VendorName, tab_Messages.Msg_Index DESC;"
                                    Case "LocationA"
                                        ' before joins this was the best it could do
                                        ' sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LocationIndex, tab_Messages.Msg_Index DESC;"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC;"
                                    Case "LocationD"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum DESC, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC;"
                                    Case "TeamA"
                                        ' before joins this was the best it could do
                                        'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Index DESC;"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Messages.Msg_Index DESC;"
                                    Case "TeamD"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder DESC, tab_Messages.Msg_Index DESC;"
                                    Case "CrDt"
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Dt DESC, tab_Messages.Msg_Tm DESC, tab_Messages.Msg_Index DESC;"
                                    Case Else
                                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"
                                        '  "Sort" to Index for the default start/finish range choices
                                        sort = "Index"
                                End Select

                            End If ' IsNumeric(frmMessageIndex)

                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Err.Number <> 0 Then
                                    Response.Write("<p>A server error occurred. Unable to load the Search Results at this time, try again later.</p>")
                                    Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                    'On Error GoTo 0
                                Else
                                    'On Error GoTo 0
                                    If sqlDataReader.HasRows = True Then

                                        ctr = 0
                                        color = "white"
                                        ' Note that date and time are separate TD fields so they can be copied into different excel columns

                                        ' only display Navbar when not searching for a message index
                                        If frmMessageIndex = "" Then
                                            ' pre-load Start
                                            ' NO, don't reset start to the first Msg_Index because depending on sort it's not the highest index in the recordset
                                            'Start = sqlDataReader.Item("Msg_Index")
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("Start=FirstIndex=" & Start & "<br>")
                                            End If

                                            ' convert from strings to numbers for the greater than/less than comparisons
                                            If IsNumeric(Max) And Max <> 0 Then
                                                Max = CLng(Max)
                                            End If
                                            If IsNumeric(Start) And Start <> 0 Then
                                                Start = CLng(Start)
                                            End If
                                            If IsNumeric(Finish) And Finish <> 0 Then
                                                Finish = CLng(Finish)
                                            End If
                                            If IsNumeric(nextStart) And nextStart <> 0 Then
                                                nextStart = CLng(nextStart)
                                            End If
                                            If IsNumeric(prevFinish) And prevFinish <> 0 Then
                                                prevFinish = CLng(prevFinish)
                                            End If

                                            ' must show the Previous - Next navigation before the table
                                            navBar = "<p>"
                                            If Start >= Max Then
                                                ' don't hyperlink
                                                navBar = navBar & "Previous -=- "
                                            Else
                                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action
                                                navBar = navBar & "&sort=" & sort & QString & "&Finish=" & prevFinish & "&nextStart=" & Start & "&Max=" & Max & """>Previous</a> -=- "
                                            End If
                                            navBar = navBar & Start & "-" & Finish
                                            If Finish <= 0 Or nextStart = Finish Then
                                                ' don't show hyperlink
                                                navBar = navBar & " -=- Next"
                                            Else
                                                navBar = navBar & " -=- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action
                                                navBar = navBar & "&sort=" & sort & QString & "&Start=" & nextStart & "&prevFinish=" & Finish & "&Max=" & Max & """>Next</a>"
                                            End If
                                            navBar = navBar & "</p>"
                                            Response.Write(navBar)

                                            If Response.Buffer = True Then
                                                'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                                                'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                                                Response.Flush()
                                            End If
                                        End If

                                        If Me.AdminType = "All" Or Me.AdminType = "FEE" Then
                                            colSpan = 12
                                        Else
                                            colSpan = 11
                                        End If
                                        Response_WriteLine("<div class=""container-fluid"">")
                                        Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed""><tbody>")
                                        If IsNumeric(frmMessageIndex) And frmMessageIndex <> "" Then
                                            ' different header for direct Index loading
                                            Response_WriteLine("<tr bgcolor=#eeeeee>")
                                            Response_WriteLine("<th>Index</th>")
                                            Response_WriteLine("<th>Complete?</th>")
                                            Response_WriteLine("<th bgcolor=""#d6dbe9"">Assigned?</th>")
                                            Response_WriteLine("<th>Location</th>")
                                            Response_WriteLine("<th>Team</th>")
                                            Response_WriteLine("<th>Last Name</th>")
                                            Response_WriteLine("<th>First Name</th>")
                                            Response_WriteLine("<th>Last 4</th>")
                                            Response_WriteLine("<th>DOB</th>")
                                            If Me.AdminType = "All" Or Me.AdminType = "FEE" Then
                                                Response_WriteLine("<th>Vendor Name</th>")
                                            End If
                                            Response_WriteLine("<th>Reason</th>")
                                            Response_WriteLine("<th nowrap>Cr.Dt</th>")
                                            Response_WriteLine("<th nowrap>Cr.Tm</th>")
                                            Response_WriteLine("</tr>")
                                        Else
                                            Response_WriteLine("<tr bgcolor=#eeeeee>")
                                            If System.Web.HttpContext.Current.Session(“Index2Sort”) = "IndexA" Then
                                                System.Web.HttpContext.Current.Session(“Index2Sort”) = "IndexD"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=IndexD" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>I</a>ndex</th>")
                                            Else
                                                System.Web.HttpContext.Current.Session(“Index2Sort”) = "IndexA"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=IndexA" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>I</a>ndex</th>")
                                            End If
                                            Response_WriteLine("<th bgcolor=""#d6dbe9""><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Complete" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>C</a>omplete?</th>")
                                            Response_WriteLine("<th bgcolor=""#d6dbe9""><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Assigned" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>A</a>ssigned?</th>")
                                            If System.Web.HttpContext.Current.Session(“Location2Sort”) = "LocationA" Then
                                                System.Web.HttpContext.Current.Session(“Location2Sort”) = "LocationD"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationD" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                            Else
                                                System.Web.HttpContext.Current.Session(“Location2Sort”) = "LocationA"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationA" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                            End If
                                            If System.Web.HttpContext.Current.Session(“Team2Sort”) = "TeamA" Then
                                                System.Web.HttpContext.Current.Session(“Team2Sort”) = "TeamD"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamD" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                            Else
                                                System.Web.HttpContext.Current.Session(“Team2Sort”) = "TeamA"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamA" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                            End If
                                            If System.Web.HttpContext.Current.Session(“LastName2Sort”) = "LastNameA" Then
                                                System.Web.HttpContext.Current.Session(“LastName2Sort”) = "LastNameD"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameD" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast Name</th>")
                                            Else
                                                System.Web.HttpContext.Current.Session(“LastName2Sort”) = "LastNameA"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameA" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast Name</th>")
                                            End If
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=FirstName" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>F</a>irst Name</th>")
                                            If System.Web.HttpContext.Current.Session(“LastFour2Sort”) = "LastFourA" Then
                                                System.Web.HttpContext.Current.Session(“LastFour2Sort”) = "LastFourD"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastFourD" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast 4</th>")
                                            Else
                                                System.Web.HttpContext.Current.Session(“LastFour2Sort”) = "LastFourA"
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastFourA" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast 4</th>")
                                            End If
                                            If Me.AdminType = "All" Or Me.AdminType = "FEE" Then
                                                Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=VendorName" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>V</a>endor Name</th>")
                                            End If
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>R</a>eason</th>")
                                            Response_WriteLine("<th nowrap><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=CrDt" & QString & "&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>C</a>r.Dt</th>")
                                            Response_WriteLine("<th nowrap>Cr.Tm</th>")
                                            Response_WriteLine("</tr>")
                                        End If
                                        While sqlDataReader.Read = True
                                            If IsDBNull(sqlDataReader.Item("Msg_Completed")) Then
                                                MCompleted = ""
                                            Else
                                                MCompleted = sqlDataReader.Item("Msg_Completed")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_Assigned")) Then
                                                MAssigned = ""
                                            Else
                                                MAssigned = sqlDataReader.Item("Msg_Assigned")
                                            End If
                                            If MAssigned = "" Then
                                                AssignedName = "&nbsp;"
                                            Else
                                                ' blank if invalid match
                                                AssignedName = Me.GetMemberNameFromUandTI(MAssigned, sqlDataReader.Item("Msg_TeamIndex"))
                                                If AssignedName = "" Then
                                                    ' since blank,  it back to the Username that is stored in tab_Messages.Msg_Assigned
                                                    ' this is due to a member's row being deleted form the Members table
                                                    ' or the username renamed w/o changing corresponding tab_Messages
                                                    AssignedName = "<font color=""red"">" & Me.CleanUserName(MAssigned) & "</font>"
                                                End If
                                            End If
                                            Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top"">")
                                            Response_WriteLine("<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>")
                                            If MCompleted = "" Then
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">" & MCompleted & "</td>")
                                            End If
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">" & AssignedName & "</td>")
                                            Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Name") & "</td>")
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                Response_WriteLine("<td><font size = 1>" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                            Else
                                                Response_WriteLine("<td><font size = 1>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Msg_LastName") & "</td>")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_FirstName")) Then
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Msg_FirstName") & "</td>")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_LastFour")) Then
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Msg_LastFour") & "</td>")
                                            End If
                                            If Me.AdminType = "All" Or Me.AdminType = "FEE" Then
                                                If IsDBNull(sqlDataReader.Item("Msg_VendorName")) Then
                                                    Response_WriteLine("<td>&nbsp;</td>")
                                                Else
                                                    Response_WriteLine("<td>" & sqlDataReader.Item("Msg_VendorName") & "</td>")
                                                End If
                                            Else
                                                ' don't show the column for other types
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_Reason")) Then
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Reason") & "</td>")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_Dt")) Then
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td align=""right"" nowrap>" & sqlDataReader.Item("Msg_Dt") & "</td>")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_Tm")) Then
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            Else
                                                Response_WriteLine("<td align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "</td>")
                                            End If
                                            Response_WriteLine("</tr>")
                                            ctr = ctr + 1
                                            If color = "white" Then
                                                color = "whitesmoke"
                                            Else
                                                color = "white"
                                            End If

                                        End While

                                        If frmMessageIndex = "" Then
                                            ' show counts when not searching for a message index
                                            Response_WriteLine("<tr><td colspan=""" & colSpan & """><center>")
                                            If ctr = 1 Then
                                                Response_WriteLine("Showing " & ctr & " Message")
                                            Else
                                                Response_WriteLine("Showing " & ctr & " Messages")
                                            End If
                                            If frmLocationIndex = "" Then
                                                If S = "" Then
                                                    Response_WriteLine(".")
                                                Else
                                                    Response_WriteLine("in site " & Me.GetSiteName(S) & ".")
                                                End If
                                            Else
                                                Response_WriteLine("in location " & Me.GetLocationName(frmLocationIndex) & ".")
                                            End If
                                            Response_WriteLine("</center></td></tr>")
                                        End If
                                        Response_WriteLine("</tbody></table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p></div></div>")
                                        ' blank when single Index so safe to show regardless
                                        Response.Write(navBar)

                                    Else
                                        If frmLocationIndex = "" Then
                                            If Me.AdminSite = "000" And IsNumeric(frmMessageIndex) Then
                                                Response_WriteLine("<p><center>No Records Found.</center></p>")
                                            Else
                                                Response_WriteLine("<p><center>No Records Found for site " & Me.GetSiteName(S) & ".</center></p>")
                                            End If
                                        Else
                                            Response_WriteLine("<p><center>No Records Found for location " & Me.GetLocationName(frmLocationIndex) & ".</center></p>")
                                        End If
                                    End If ' sqlDataReader end
                                End If ' err.number <> 0

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            'On Error Resume Next

                        End If ' 3 fields Nothing
                    End If ' formused = "Yes"

                Case "MySent"
                    'New DevExpress replacing old/old school but isn't quite ready for DataTables implementation
                    'Response.Redirect("~/MySent.aspx", True) ' for 3 tables all needing own DT conversions
                    ' ---
                    ' view "My Sent Messages"
                    ' ---
                    Response_WriteLine("<p><b><big>My Sent Messages</big></b></p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    ' this query takes between 2 and 30 seconds, skip the check if server overloaded in last 5 minutes 
                    ' (prevents user from double clicking My Sent or going crazy navigating it)
                    sec = Me.SecSinceOverload()
                    If sec >= 0 And sec < 120 Then
                        ' skip this now, server too busy
                        Response_WriteLine("<p>Server too busy within last 2 minutes to load ""My Sent"".  Try again later.</p>")
                    Else

                        ' get Start and Finish range
                        ' GROUPS of 100
                        blockSize = 100
                        ' begin with the Max
                        sSqlString = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM tab_Messages"
                        ' do not filter by site.  Could have sent messages to other sites.
                        sSqlString = sSqlString & " WHERE tab_Messages.Msg_Username LIKE '" & Replace(Me.UserName, "'", "''") & "';"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = False Then
                                Max = 0
                            Else
                                If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                    Max = 0
                                Else
                                    Max = sqlDataReader.Item("MAXINDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        '  Start to Max if not pre-chosen
                        If (Not Request.QueryString("Start") Is Nothing) Then Start = Request.QueryString("Start").ToString() Else Start = ""
                        If (Not Request.QueryString("Finish") Is Nothing) Then Finish = Request.QueryString("Finish").ToString() Else Finish = ""
                        If Start.ToString = "" Or IsDBNull(Start) Then
                            Start = Max
                        Else
                            ' Start chosen
                        End If

                        If Finish.ToString = "" Or IsDBNull(Finish) Then
                            '  Finish to be the smallest Index of top "blockSize" messages below Start
                            sSqlString = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index FROM tab_Messages" & " WHERE tab_Messages.Msg_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " AND tab_Messages.Msg_Index <= " & Start & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If sqlDataReader.Read = False Then
                                    Finish = 0
                                Else
                                    If IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                        Finish = 0
                                    Else
                                        Finish = sqlDataReader.Item("MININDEX")
                                    End If
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                        Else
                            ' Finish is chosen
                            '  Start to be the highest index of the top "blockSize" messages above Finish
                            sSqlString = "SELECT MAX(tab_derived_Msg.Msg_Index) AS MAXINDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index FROM tab_Messages" & " WHERE tab_Messages.Msg_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " AND tab_Messages.Msg_Index >= " & Finish & " ORDER BY tab_Messages.Msg_Index ASC) AS tab_derived_Msg;"

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If sqlDataReader.Read = False Then
                                    Start = ""
                                Else
                                    If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                        Start = ""
                                    Else
                                        Start = sqlDataReader.Item("MAXINDEX")
                                    End If
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                        End If

                        ' convert from strings to numbers for the greater than/less than comparisons
                        If IsNumeric(Max) And Max <> 0 Then
                            Max = CLng(Max)
                        End If
                        If IsNumeric(Start) And Start <> 0 Then
                            Start = CLng(Start)
                        End If
                        If IsNumeric(Finish) And Finish <> 0 Then
                            Finish = CLng(Finish)
                        End If

                        If Max = 0 Then
                            ' nothing to view
                            Response_WriteLine("<p>No Sent Messages exist.</p>")
                        Else
                            navBar = "<p>"
                            If IsNumeric(Start) Then
                                If Start + 1 >= Max Then
                                    ' no previous hyperlink
                                    navBar = navBar & "Previous"
                                Else
                                    navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Finish=" & Start + 1
                                    navBar = navBar & "&action=" & action & "&sort=" & sort & """>Previous</a>"
                                End If
                            End If
                            navBar = navBar & " -=- " & Start & "-" & Finish & " -=- "
                            If IsNumeric(Finish) Then
                                If Finish - 1 <= 0 Then
                                    ' no next hyperlink
                                    navBar = navBar & " Next"
                                Else
                                    navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Start=" & Finish - 1
                                    navBar = navBar & "&action=" & action & "&sort=" & sort & """>Next</a>"
                                End If
                            End If
                            navBar = navBar & "</p>"
                            Response.Write(navBar)

                            If Response.Buffer = True Then
                                'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                                'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                                Response.Flush()
                            End If

                            ' Now load the group of "blockSize" messages based on the calculated Start and Finish
                            sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Assigned," & " tab_Messages.Msg_SiteNum, tab_Messages.Msg_TeamIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name," & " tab_Messages.Msg_Reason, tab_Messages.Msg_LastName, tab_Messages.Msg_LastFour, tab_Messages.Msg_DOB," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm, tab_Audit.Au_Action" & " FROM ((tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_Index <= " & Start & " AND tab_Messages.Msg_Index >= " & Finish & " AND tab_Messages.Msg_Username LIKE '" & Replace(Me.UserName, "'", "''") & "'" & " AND (tab_Audit.Au_Action <> 'Assigned' OR tab_Audit.Au_Action IS NULL)"

                            ' sorting by Action ASCENDING will put "Completed" in the first slot as value 'Assigned' is excluded
                            Select Case sort
                                Case "IndexD"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "IndexA"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC, tab_Audit.Au_Action ASC;"
                                Case "Assigned"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Assigned, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "Reason"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Reason, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "LastNameA"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "LastNameD"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "Last4"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastFour, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "Site"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "LocationA"
                                    ' before joins this was the best it could do
                                    'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LocationIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "LocationD"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum DESC, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "TeamA"
                                    ' before joins this was the best it could do
                                    'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "TeamD"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case "CrDt"
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Dt DESC, tab_Messages.Msg_Tm DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                Case Else
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                    '  "Sort" to Index for the default start/finish range choices
                                    sort = "Index"
                            End Select

                            'On Error Resume Next

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Err.Number <> 0 Then
                                    Response.Write("<p>A server error occurred. Unable to load My Sent messages at this time, try again later.</p>")
                                    Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                    'On Error GoTo 0
                                Else
                                    'On Error GoTo 0
                                    If Not sqlDataReader.HasRows Then
                                        ' specified Site not found in db
                                        If Me.SiteName = "" Then
                                            Response_WriteLine("<p>No site chosen, no Sent Messages available.</p>")
                                        Else
                                            Response_WriteLine("<p>No Sent Messages for " & Me.SiteName & " within Index range " & Start & "-" & Finish & ".</p>")
                                        End If
                                    Else
                                        ctr = 0
                                        color = "white"
                                        lastIndex = 0
                                        Response_WriteLine("<div class=""container-fluid"">")
                                        Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed""><tbody>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""bottom"">")
                                        If System.Web.HttpContext.Current.Session(“Index3Sort”) = "IndexA" Then
                                            System.Web.HttpContext.Current.Session(“Index3Sort”) = "IndexD"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=IndexD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>I</a>ndex</th>")
                                        Else
                                            System.Web.HttpContext.Current.Session(“Index3Sort”) = "IndexA"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=IndexA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>I</a>ndex</th>")
                                        End If
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Site&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>S</a>ite</th>")
                                        If System.Web.HttpContext.Current.Session(“Location3Sort”) = "LocationA" Then
                                            System.Web.HttpContext.Current.Session(“Location3Sort”) = "LocationD"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                        Else
                                            System.Web.HttpContext.Current.Session(“Location3Sort”) = "LocationA"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                        End If
                                        If System.Web.HttpContext.Current.Session(“Team3Sort”) = "TeamA" Then
                                            System.Web.HttpContext.Current.Session(“Team3Sort”) = "TeamD"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                        Else
                                            System.Web.HttpContext.Current.Session(“Team3Sort”) = "TeamA"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                        End If
                                        If System.Web.HttpContext.Current.Session(“LastName3Sort”) = "LastNameA" Then
                                            System.Web.HttpContext.Current.Session(“LastName3Sort”) = "LastNameD"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast Name</th>")
                                        Else
                                            System.Web.HttpContext.Current.Session(“LastName3Sort”) = "LastNameA"
                                            Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast Name</th>")
                                        End If
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Last4&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast 4</th>")
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>R</a>eason</th>")
                                        Response_WriteLine("<th nowrap><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=CrDt&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>C</a>r.Dt</th>")
                                        Response_WriteLine("<th nowrap>Cr.Tm</th>")
                                        Response_WriteLine("<th>Done</th>")
                                        Response_WriteLine("<th nowrap>BH</th>")
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Assigned&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>A</a>ssignee</th>")
                                        Response_WriteLine("</tr>")
                                        While sqlDataReader.Read = True And ctr <= blockSize

                                            If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                                ' skip, same (the rest of the Audit records)
                                            Else
                                                ' different, show it

                                                ctr = ctr + 1
                                                If color = "white" Then
                                                    color = "whitesmoke"
                                                Else
                                                    color = "white"
                                                End If

                                                If IsDBNull(sqlDataReader.Item("Msg_Completed")) Then
                                                    MCompleted = ""
                                                Else
                                                    MCompleted = sqlDataReader.Item("Msg_Completed")
                                                End If
                                                If IsDBNull(sqlDataReader.Item("Msg_Assigned")) Then
                                                    MAssigned = ""
                                                Else
                                                    MAssigned = sqlDataReader.Item("Msg_Assigned")
                                                End If
                                                If MAssigned = "" Then
                                                    AssignedName = "&nbsp;"
                                                Else
                                                    ' blank if invalid match
                                                    AssignedName = Me.GetMemberNameFromUandTI(MAssigned, sqlDataReader.Item("Msg_TeamIndex"))
                                                    If AssignedName = "" Then
                                                        ' since blank,  it back to the Username that is stored in tab_Messages.Msg_Assigned
                                                        ' this is due to a member's row being deleted form the Members table
                                                        ' or the username renamed w/o changing corresponding tab_Messages
                                                        AssignedName = "<font color=""red"">" & Me.CleanUserName(MAssigned) & "</font>"
                                                    End If
                                                End If
                                                Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top"">")
                                                Response_WriteLine("<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>")
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Msg_SiteNum") & "</td>")
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Name") & "</td>")
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine("<td><font size = 1>" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                                Else
                                                    Response_WriteLine("<td><font size = 1>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                                End If
                                                Response_WriteLine("<td>")
                                                If IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                                    Response_WriteLine("&nbsp;")
                                                Else
                                                    Response_WriteLine("" & sqlDataReader.Item("Msg_LastName") & "")
                                                End If
                                                Response_WriteLine("</td>")
                                                Response_WriteLine("<td>")
                                                If IsDBNull(sqlDataReader.Item("Msg_LastFour")) Then
                                                    Response_WriteLine("&nbsp;")
                                                Else
                                                    Response_WriteLine("" & sqlDataReader.Item("Msg_LastFour") & "")
                                                End If
                                                Response_WriteLine("</td>")
                                                Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Reason") & "</td>")
                                                Response_WriteLine("<td align=""right"" nowrap>" & sqlDataReader.Item("Msg_Dt") & "</td>")
                                                Response_WriteLine("<td align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "</td>")
                                                If MCompleted = "Yes" Then
                                                    Response_WriteLine("<td>Yes</td>")
                                                    Response_WriteLine("<td nowrap>" & Me.roundClock(Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "BH")) & "</td>")
                                                Else
                                                    Response_WriteLine("<td>&nbsp;</td>")
                                                    Response_WriteLine("<td>&nbsp;</td>")
                                                End If
                                                Response_WriteLine("<td>" & AssignedName & "</td>")
                                                Response_WriteLine("</tr>")
                                                lastIndex = sqlDataReader.Item("Msg_Index")
                                            End If

                                        End While
                                        Response_WriteLine("<tr><td colspan=""12""><center>Showing records " & Start & " through " & Finish & " = " & ctr & " Messages.</center></td></tr>")
                                        Response_WriteLine("</tbody></table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p></div></div>")
                                        Response.Write(navBar)
                                    End If
                                End If ' err.number <> 0

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                        End If ' Max = 0
                    End If  ' sec >= 0 and sec < 120

                Case "Audit"
                    ' ---
                    ' View Audit Log
                    ' ---
                    Response_WriteLine("<p><b><big>Audit Log</big></b><br>")
                    Response_WriteLine("Any view of a Message will generate an audit record.  Here they are:</p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    ' get Start and Finish range
                    ' GROUPS of 100
                    blockSize = 100
                    ' begin with the Max
                    sSqlString = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM tab_Messages WHERE tab_Messages.Msg_SiteNum = '" & S & "';"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.Read = False Then
                            Max = 0
                        Else
                            If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                Max = 0
                            Else
                                Max = sqlDataReader.Item("MAXINDEX")
                            End If
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    '  Start to Max if not pre-chosen
                    If (Not Request.QueryString("Start") Is Nothing) Then Start = Request.QueryString("Start").ToString() Else Start = ""
                    If (Not Request.QueryString("Finish") Is Nothing) Then Finish = Request.QueryString("Finish").ToString() Else Finish = ""
                    If Start.ToString = "" Then
                        Start = Max
                    Else
                        ' Start chosen
                    End If

                    If Finish.ToString = "" Then
                        '  Finish to be the smallest Index of top "blockSize" messages below Start
                        sSqlString = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index FROM tab_Messages" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index <= " & Start
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = False Then
                                Finish = 0
                            Else
                                If IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                    Finish = 0
                                Else
                                    Finish = sqlDataReader.Item("MININDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Else
                        ' Finish is chosen
                        '  Start to be the highest index of the top "blockSize" messages above Finish
                        sSqlString = "SELECT MAX(tab_derived_Msg.Msg_Index) AS MAXINDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index FROM tab_Messages" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index >= " & Finish
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC) AS tab_derived_Msg;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = True Then
                                If Not IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                    Start = sqlDataReader.Item("MAXINDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If

                    ' convert from strings to numbers for the greater than/less than comparisons
                    If IsNumeric(Max) And Max <> 0 Then
                        Max = CLng(Max)
                    End If
                    If IsNumeric(Start) And Start <> 0 Then
                        Start = CLng(Start)
                    End If
                    If IsNumeric(Finish) And Finish <> 0 Then
                        Finish = CLng(Finish)
                    End If

                    If Max = 0 Then
                        ' nothing to view
                        If Me.SiteName = "" Then
                            Response_WriteLine("<p>No site chosen.</p>")
                        Else
                            Response_WriteLine("<p>No Audit records exist.</p>")
                        End If
                    Else
                        navBar = "<p>"
                        If IsNumeric(Start) Then
                            If Start + 1 >= Max Then
                                ' no previous hyperlink
                                navBar = navBar & "Previous"
                            Else
                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Finish=" & Start + 1
                                navBar = navBar & "&action=" & action & """>Previous</a>"
                            End If
                        End If

                        navBar = navBar & " -=- " & Start & "-" & Finish & " -=- "

                        If IsNumeric(Finish) Then
                            If Finish - 1 <= 0 Then
                                ' no next hyperlink
                                navBar = navBar & " Next"
                            Else
                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Start=" & Finish - 1
                                navBar = navBar & "&action=" & action & """>Next</a>"
                            End If
                        End If
                        navBar = navBar & "</p>"
                        Response.Write(navBar)

                        If Response.Buffer = True Then
                            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                            'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                            Response.Flush()
                        End If

                        ' Now load the group of "blocksize" messages based on the calculated Start and Finish
                        sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Messages.Msg_Username," & " tab_Audit.Au_Action, tab_Audit.Au_Dt, tab_Audit.Au_Tm, tab_Audit.Au_Username" & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index <= " & Start & " AND tab_Messages.Msg_Index >= " & Finish
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                If Me.SiteName = "" Then
                                    Response_WriteLine("<p>No site chosen, no audit available.</p>")
                                Else
                                    Response_WriteLine("<p>No Audit Records exist for Site " & Me.SiteName & "</p>")
                                End If
                            Else
                                ctr = 0
                                lastIndex = 0
                                color = "white"
                                Response_WriteLine("<div class=""container-fluid"">")
                                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"">")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9"">")
                                Response_WriteLine("<th>Index</th>")
                                Response_WriteLine("<th>Action</th>")
                                Response_WriteLine("<th>Date</th>")
                                Response_WriteLine("<th>Time</th>")
                                Response_WriteLine("<th>User</th>")
                                Response_WriteLine("</tr>")
                                While sqlDataReader.Read = True And ctr <= blockSize
                                    If sqlDataReader.Item("Msg_Index") = lastIndex Then
                                        ' show no tab_Messages info, just tab_Audit info
                                    Else
                                        ctr = ctr + 1
                                        lastIndex = sqlDataReader.Item("Msg_Index")
                                        If color = "white" Then
                                            color = "whitesmoke"
                                        Else
                                            color = "white"
                                        End If
                                        ' first show the Creation timestamp
                                        Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top"">")
                                        Response_WriteLine("<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>")
                                        Response_WriteLine("<td>Created</td>")
                                        Response_WriteLine("<td align=""right"">" & sqlDataReader.Item("Msg_Dt") & "</td>")
                                        Response_WriteLine("<td align=""right"">" & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "</td>")
                                        Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Username") & "</td>")
                                        Response_WriteLine("</tr>")
                                    End If
                                    If Not IsDBNull(sqlDataReader.Item("Au_Action")) Then
                                        Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top"">")
                                        Response_WriteLine("<td>&nbsp;</td>")
                                        Response_WriteLine("<td>" & sqlDataReader.Item("Au_Action") & "</td>")
                                        Response_WriteLine("<td align=""right"">" & sqlDataReader.Item("Au_Dt") & "</td>")
                                        Response_WriteLine("<td align=""right"">" & Me.formatTime(sqlDataReader.Item("Au_Tm"), False) & "</td>")
                                        Response_WriteLine("<td>" & sqlDataReader.Item("Au_Username") & "</td>")
                                        Response_WriteLine("</tr>")
                                    End If
                                End While
                                Response_WriteLine("<tr><td colspan=""5""><center>Showing " & Start & " through " & Finish & " = " & ctr & " records shown in " & Me.SiteName & ".</center></td></tr>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p></div></div>")
                                Response.Write(navBar)
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If ' Max = 0

                Case "History"
                    ' ---
                    ' view Processing History
                    ' ---
                    Response_WriteLine("<p><b><big>Processing History</big></b></p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    ' get Start and Finish range
                    ' GROUPS of 500
                    blockSize = 500
                    ' begin with the Max
                    sSqlString = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM tab_Messages WHERE tab_Messages.Msg_SiteNum = '" & S & "';"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.Read = False Then
                            Max = 0
                        Else
                            If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                Max = 0
                            Else
                                Max = sqlDataReader.Item("MAXINDEX")
                            End If
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    '  Start to Max if not pre-chosen
                    If (Not Request.QueryString("Start") Is Nothing) Then Start = Request.QueryString("Start").ToString() Else Start = ""
                    If (Not Request.QueryString("Finish") Is Nothing) Then Finish = Request.QueryString("Finish").ToString() Else Finish = ""
                    If Start.ToString = "" Then
                        Start = Max
                    Else
                        ' Start chosen
                    End If

                    If Finish.ToString = "" Then
                        '  Finish to be the smallest Index of top "blockSize" messages below Start
                        sSqlString = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index FROM tab_Messages" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index <= " & Start
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = False Then
                                Finish = 0
                            Else
                                If IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                    Finish = 0
                                Else
                                    Finish = sqlDataReader.Item("MININDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Else
                        ' Finish is chosen
                        '  Start to be the highest index of the top "blockSize" messages above Finish
                        sSqlString = "SELECT MAX(tab_derived_Msg.Msg_Index) AS MAXINDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index FROM tab_Messages" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index >= " & Finish
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC) AS tab_derived_Msg;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = False Then
                                ' nothing found above it.   start to be Max instead
                                Start = Max
                            Else
                                If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                    ' nothing found above it.   start to be Max instead
                                    Start = Max
                                Else
                                    Start = sqlDataReader.Item("MAXINDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If

                    ' convert from strings to numbers for the greater than/less than comparisons
                    If IsNumeric(Max) And Max <> 0 Then
                        Max = CLng(Max)
                    End If
                    If IsNumeric(Start) And Start <> 0 Then
                        Start = CLng(Start)
                    End If
                    If IsNumeric(Finish) And Finish <> 0 Then
                        Finish = CLng(Finish)
                    End If

                    If Max = 0 Then
                        ' nothing to view
                        If Me.SiteName = "" Then
                            Response_WriteLine("<p>No site chosen.</p>")
                        Else
                            Response_WriteLine("<p>No Processing History exists.</p>")
                        End If
                    Else

                        navBar = "<p>"
                        If IsNumeric(Start) Then
                            If Start + 1 >= Max Then
                                ' no previous hyperlink
                                navBar = navBar & "Previous"
                            Else
                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Finish=" & Start + 1
                                navBar = navBar & "&action=" & action & "&sort=" & sort & """>Previous</a>"
                            End If
                        End If

                        navBar = navBar & " -=- " & Start & "-" & Finish & " -=- "

                        If IsNumeric(Finish) Then
                            If Finish - 1 <= 0 Then
                                ' no next hyperlink
                                navBar = navBar & " Next"
                            Else
                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Start=" & Finish - 1
                                navBar = navBar & "&action=" & action & "&sort=" & sort & """>Next</a>"
                            End If
                        End If
                        navBar = navBar & "</p>"
                        Response.Write(navBar)

                        ' Now load the group of "blockSize" messages based on the calculated Start and Finish
                        sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Assigned," & " tab_Messages.Msg_TeamIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name," & " tab_Messages.Msg_Reason, tab_Messages.Msg_LastName, tab_Messages.Msg_LastFour, tab_Messages.Msg_DOB," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm," & " tab_Audit.Au_Dt, tab_Audit.Au_Tm" & " FROM ((tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'"
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " AND tab_Messages.Msg_Index <= " & Start & " AND tab_Messages.Msg_Index >= " & Finish & " AND (tab_Audit.Au_Action <> 'Assigned' OR tab_Audit.Au_Action IS NULL)"

                        ' sorting by Action ASCENDING will put "Completed" in the first slot as value 'Assigned' is excluded
                        Select Case sort
                            Case "IndexD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "IndexA"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC, tab_Audit.Au_Action ASC;"
                            Case "Assigned"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Assigned, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "Reason"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Reason, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "LastNameA"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "LastNameD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastName DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "Last4"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LastFour, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "LocationA"
                                ' before joins this was the best it could do
                                'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LocationIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "LocationD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum DESC, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "TeamA"
                                ' before joins this was the best it could do
                                'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "TeamD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "CrDt"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Dt DESC, tab_Messages.Msg_Tm DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case Else
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                '  "Sort" to Index for the default start/finish range choices
                                sort = "Index"
                        End Select

                        'On Error Resume Next

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Err.Number <> 0 Then
                                Response.Write("<p>A server error occurred. Unable to load History at this time, try again later.</p>")
                                Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                'On Error GoTo 0
                            Else
                                If Not sqlDataReader.HasRows Then
                                    ' specified Site not found in db
                                    If Me.SiteName = "" Then
                                        Response_WriteLine("<p>No site chosen, no history available.</p>")
                                    Else
                                        Response_WriteLine("<p>No History for " & Me.SiteName & " within Index range " & Start & "-" & Finish & ".</p>")
                                    End If
                                Else
                                    ctr = 0
                                    color = "white"
                                    lastIndex = 0

                                    If Response.Buffer = True Then
                                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                                        Response.Flush()
                                    End If
                                    Response_WriteLine("<div class=""container-fluid"">")
                                    Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                    Response_WriteLine("<p>")
                                    Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                    Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed""><tbody>")
                                    Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""bottom"">")
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>I</a>ndex</th>")
                                    If System.Web.HttpContext.Current.Session(“Location4Sort”) = "LocationA" Then
                                        System.Web.HttpContext.Current.Session(“Location4Sort”) = "LocationD"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                    Else
                                        System.Web.HttpContext.Current.Session(“Location4Sort”) = "LocationA"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                    End If
                                    If System.Web.HttpContext.Current.Session(“Team4Sort”) = "TeamA" Then
                                        System.Web.HttpContext.Current.Session(“Team4Sort”) = "TeamD"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                    Else
                                        System.Web.HttpContext.Current.Session(“Team4Sort”) = "TeamA"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                    End If
                                    If System.Web.HttpContext.Current.Session(“LastName4Sort”) = "LastNameA" Then
                                        System.Web.HttpContext.Current.Session(“LastName4Sort”) = "LastNameD"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast Name</th>")
                                    Else
                                        System.Web.HttpContext.Current.Session(“LastName4Sort”) = "LastNameA"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LastNameA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast Name</th>")
                                    End If
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Last4&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ast4</th>")
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>R</a>eason</th>")
                                    Response_WriteLine("<th nowrap><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=CrDt&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>C</a>r.Dt</th>")
                                    Response_WriteLine("<th nowrap>Cr.Tm</th>")
                                    Response_WriteLine("<th>Done</th>")
                                    Response_WriteLine("<th>BH</th>")
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Assigned&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>A</a>ssignee</th>")
                                    Response_WriteLine("</tr>")
                                    While sqlDataReader.Read = True And ctr <= blockSize

                                        If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                            ' skip, same (the rest of the Audit records)
                                        Else
                                            ' different, show it

                                            ctr = ctr + 1
                                            If color = "white" Then
                                                color = "whitesmoke"
                                            Else
                                                color = "white"
                                            End If

                                            If IsDBNull(sqlDataReader.Item("Msg_Completed")) Then
                                                MCompleted = ""
                                            Else
                                                MCompleted = sqlDataReader.Item("Msg_Completed")
                                            End If
                                            If IsDBNull(sqlDataReader.Item("Msg_Assigned")) Then
                                                MAssigned = ""
                                                AssignedName = "&nbsp;"
                                            Else
                                                MAssigned = sqlDataReader.Item("Msg_Assigned")
                                                ' blank if invalid match
                                                AssignedName = Me.GetMemberNameFromUandTI(MAssigned, sqlDataReader.Item("Msg_TeamIndex"))
                                                If AssignedName = "" Then
                                                    ' since blank,  it back to the Username that is stored in tab_Messages.Msg_Assigned
                                                    ' this is due to a member's row being deleted form the Members table
                                                    ' or the username renamed w/o changing corresponding tab_Messages
                                                    AssignedName = "<font color=""red"">" & Me.CleanUserName(MAssigned) & "</font>"
                                                End If
                                            End If
                                            Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top"">")
                                            Response_WriteLine("<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>")
                                            Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Name") & "</td>")
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                Response_WriteLine("<td><font size = 1>" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                            Else
                                                Response_WriteLine("<td><font size = 1>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                            End If
                                            Response_WriteLine("<td>")
                                            If IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                                Response_WriteLine("&nbsp;")
                                            Else
                                                Response_WriteLine("" & sqlDataReader.Item("Msg_LastName") & "")
                                            End If
                                            Response_WriteLine("</td>")
                                            Response_WriteLine("<td>")
                                            If IsDBNull(sqlDataReader.Item("Msg_LastFour")) Then
                                                Response_WriteLine("&nbsp;")
                                            Else
                                                Response_WriteLine("" & sqlDataReader.Item("Msg_LastFour") & "")
                                            End If
                                            Response_WriteLine("</td>")
                                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Reason") & "</td>")
                                            Response_WriteLine("<td align=""right"" nowrap>" & sqlDataReader.Item("Msg_Dt") & "</td>")
                                            Response_WriteLine("<td align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "</td>")
                                            If MCompleted = "Yes" Then
                                                Response_WriteLine("<td>Yes</td>")
                                                Response_WriteLine("<td align=""right"">" & Me.roundClock(Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "BH")) & "</td>")
                                            Else
                                                Response_WriteLine("<td>&nbsp;</td>")
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            End If
                                            Response_WriteLine("<td>" & AssignedName & "</td>")
                                            Response_WriteLine("</tr>")
                                            lastIndex = sqlDataReader.Item("Msg_Index")
                                        End If

                                    End While
                                    Response_WriteLine("<tr><td colspan=""11""><center>Showing records " & Start & " through " & Finish & " = " & ctr & " Messages in " & Me.SiteName & ".</center></td></tr>")
                                    Response_WriteLine("</tbody></table>")
                                    Response_WriteLine("</td></tr></table>")
                                    Response_WriteLine("</p></div></div>")
                                    Response.Write(navBar)
                                    Response_WriteLine("<p><b>BH</b> = time elapsed in Business Hours (8a-5p) between creation and closure of Message.</p>")
                                End If

                            End If ' err.number <> 0

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If ' Max = 0

                Case "Flagged"
                    ' ---
                    ' view Flgged Messages
                    ' ---
                    Dim flagArray, flagUBound, flagMSG
                    Response_WriteLine("<p><b><big>Flagged Messages</big></b></p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    ' get Start and Finish range
                    ' GROUPS of 500 (TJD - 9/6/2024 - System performance prevents us from doing 500 at a time. Reducing now to 100)
                    blockSize = 100
                    ' begin with the Max
                    sSqlString = "SELECT MAX(tab_Messages.Msg_Index) AS MAXINDEX FROM tab_Messages WHERE tab_Messages.Msg_SiteNum = '" & S & "';"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.Read = False Then
                            Max = 0
                        Else
                            If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                Max = 0
                            Else
                                Max = sqlDataReader.Item("MAXINDEX")
                            End If
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    '  Start to Max if not pre-chosen
                    If (Not Request.QueryString("Start") Is Nothing) Then Start = Request.QueryString("Start").ToString() Else Start = ""
                    If (Not Request.QueryString("Finish") Is Nothing) Then Finish = Request.QueryString("Finish").ToString() Else Finish = ""
                    If Start.ToString = "" Then
                        Start = Max
                    Else
                        ' Start chosen
                    End If

                    If Finish.ToString = "" Then
                        '  Finish to be the smallest Index of top "blockSize" messages below Start
                        sSqlString = "SELECT MIN(tab_derived_Msg.Msg_Index) AS MININDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index" & " FROM (tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index <= " & Start & " AND tab_Audit.Au_Action = 'Flag'"
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC) AS tab_derived_Msg;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = False Then
                                Finish = 0
                            Else
                                If IsDBNull(sqlDataReader.Item("MININDEX")) Then
                                    Finish = 0
                                Else
                                    Finish = sqlDataReader.Item("MININDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Else
                        ' Finish is chosen
                        '  Start to be the highest index of the top "blockSize" messages above Finish
                        sSqlString = "SELECT MAX(tab_derived_Msg.Msg_Index) AS MAXINDEX FROM (SELECT TOP " & blockSize & " tab_Messages.Msg_Index" & " FROM (tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'" & " AND tab_Messages.Msg_Index >= " & Finish & " AND tab_Audit.Au_Action = 'Flag'"
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC) AS tab_derived_Msg;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = False Then
                                ' nothing found above it.   start to be Max instead
                                Start = Max
                            Else
                                If IsDBNull(sqlDataReader.Item("MAXINDEX")) Then
                                    ' nothing found above it.   start to be Max instead
                                    Start = Max
                                Else
                                    Start = sqlDataReader.Item("MAXINDEX")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If

                    ' convert from strings to numbers for the greater than/less than comparisons
                    If IsNumeric(Max) And Max <> 0 Then
                        Max = CLng(Max)
                    End If
                    If IsNumeric(Start) And Start <> 0 Then
                        Start = CLng(Start)
                    End If
                    If IsNumeric(Finish) And Finish <> 0 Then
                        Finish = CLng(Finish)
                    End If

                    If Max = 0 Then
                        ' nothing to view
                        If Me.SiteName = "" Then
                            Response_WriteLine("<p>No site chosen.</p>")
                        Else
                            Response_WriteLine("<p>No Flagged Messages exist.</p>")
                        End If
                    Else

                        navBar = "<p>"
                        If IsNumeric(Start) Then
                            If Start + 1 >= Max Then
                                ' no previous hyperlink
                                navBar = navBar & "Previous"
                            Else
                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Finish=" & Start + 1
                                navBar = navBar & "&action=" & action & "&sort=" & sort & """>Previous</a>"
                            End If
                        End If

                        navBar = navBar & " -=- " & Start & "-" & Finish & " -=- "

                        If IsNumeric(Finish) Then
                            If Finish - 1 <= 0 Then
                                ' no next hyperlink
                                navBar = navBar & " Next"
                            Else
                                navBar = navBar & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&Start=" & Finish - 1
                                navBar = navBar & "&action=" & action & "&sort=" & sort & """>Next</a>"
                            End If
                        End If
                        navBar = navBar & "</p>"
                        Response.Write(navBar)

                        ' Now load the group of "blockSize" messages based on the calculated Start and Finish
                        sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Username," & " tab_Messages.Msg_TeamIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name," & " tab_Messages.Msg_Reason, tab_Messages.Msg_Dt, tab_Messages.Msg_Tm," & " tab_Audit.Au_Dt, tab_Audit.Au_Tm, Au_Username, tab_Audit.Au_Detail" & " FROM ((tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index)" & " LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_SiteNum = '" & S & "'"
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                        End If
                        sSqlString = sSqlString & " AND tab_Messages.Msg_Index <= " & Start & " AND tab_Messages.Msg_Index >= " & Finish & " AND (tab_Audit.Au_Action = 'Flag')"

                        ' sorting by Action ASCENDING will put "Completed" in the first slot as value 'Assigned' is excluded
                        Select Case sort
                            Case "IndexD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "IndexA"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index ASC, tab_Audit.Au_Action ASC;"
                            Case "Creator"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Username, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "Reason"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Reason, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "LocationA"
                                ' before joins this was the best it could do
                                'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_LocationIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "LocationD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum DESC, tab_Locations.Lo_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "TeamA"
                                ' before joins this was the best it could do
                                'sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "TeamD"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case "CrDt"
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Dt DESC, tab_Messages.Msg_Tm DESC, tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                            Case Else
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Action ASC;"
                                '  "Sort" to Index for the default start/finish range choices
                                sort = "Index"
                        End Select

                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If
                        'On Error Resume Next

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Err.Number <> 0 Then
                                Response.Write("<p>A server error occurred. Unable to load History at this time, try again later.</p>")
                                Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                'On Error GoTo 0
                            Else

                                If Not sqlDataReader.HasRows Then
                                    ' specified Site not found in db
                                    If Me.SiteName = "" Then
                                        Response_WriteLine("<p>No site chosen, no history available.</p>")
                                    Else
                                        Response_WriteLine("<p>No History for " & Me.SiteName & " within Index range " & Start & "-" & Finish & ".</p>")
                                    End If
                                Else
                                    ctr = 0
                                    color = "white"
                                    lastIndex = 0

                                    If Response.Buffer = True Then
                                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                                        Response.Flush()
                                    End If
                                    Response_WriteLine("<div class=""container-fluid"">")
                                    Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                    Response_WriteLine("<p>")
                                    Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                    Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed""><tbody>")
                                    Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""bottom"">")
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>I</a>ndex</th>")
                                    If System.Web.HttpContext.Current.Session(“Location5Sort”) = "LocationA" Then
                                        System.Web.HttpContext.Current.Session(“Location5Sort”) = "LocationD"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                    Else
                                        System.Web.HttpContext.Current.Session(“Location5Sort”) = "LocationA"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=LocationA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>L</a>ocation</th>")
                                    End If
                                    If System.Web.HttpContext.Current.Session(“Team5Sort”) = "TeamA" Then
                                        System.Web.HttpContext.Current.Session(“Team5Sort”) = "TeamD"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamD&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                    Else
                                        System.Web.HttpContext.Current.Session(“Team5Sort”) = "TeamA"
                                        Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=TeamA&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>T</a>eam</th>")
                                    End If
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Reason&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>R</a>eason</th>")
                                    Response_WriteLine("<th nowrap><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=CrDt&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>C</a>r.Dt</th>")
                                    Response_WriteLine("<th nowrap>Cr.Tm</th>")
                                    Response_WriteLine("<th>Done</th>")
                                    Response_WriteLine("<th>BH</th>")
                                    Response_WriteLine("<th><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & I & "&action=" & action & "&sort=Creator&Start=" & Start & "&Finish=" & Finish & "&Max=" & Max & """>C</a>reator</th>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""bottom"">")
                                    Response_WriteLine("<th>&nbsp;</th>")
                                    Response_WriteLine("<th colspan=""3"" align=""left"">Flag Reason</th>")
                                    Response_WriteLine("<th nowrap align=""left"">Flag.Dt</th>")
                                    Response_WriteLine("<th nowrap align=""right"">Flag.Tm</th>")
                                    Response_WriteLine("<th colspan=""3"" align=""left"">Flagged By</th>")
                                    Response_WriteLine("</tr>")
                                    While sqlDataReader.Read = True And ctr <= blockSize

                                        If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                            ' multiple flags for same message! (the rest of the Audit records)
                                            ' show the flag at the new row
                                        Else
                                            ' different, show it

                                            ctr = ctr + 1
                                            If color = "white" Then
                                                color = "whitesmoke"
                                            Else
                                                color = "white"
                                            End If

                                            If IsDBNull(sqlDataReader.Item("Msg_Completed")) Then
                                                MCompleted = ""
                                            Else
                                                MCompleted = sqlDataReader.Item("Msg_Completed")
                                            End If
                                            ' using MAssigned variable to store Msg_Username which is the Message Creator
                                            MAssigned = sqlDataReader.Item("Msg_Username")
                                            If IsDBNull(MAssigned) Then
                                                MAssigned = ""
                                                AssignedName = "&nbsp;"
                                            Else
                                                ' blank if invalid match.
                                                AssignedName = Me.GetMemberNameFlaggedUandTI(MAssigned, sqlDataReader.Item("Msg_TeamIndex"))
                                                If AssignedName = "" Then
                                                    ' since blank,  it back to the Username that is stored in tab_Messages
                                                    ' this is due to the fact that most message creators are not in the team
                                                    AssignedName = Me.CleanUserName(MAssigned) & " - " & Me.PollMemberNameForLogin(MAssigned)
                                                End If
                                            End If
                                            Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top"">")
                                            Response_WriteLine("<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & "&action=" & action & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>")
                                            Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Name") & "</td>")
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                Response_WriteLine("<td><font size = 1>" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                            Else
                                                Response_WriteLine("<td><font size = 1>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</font></td>")
                                            End If
                                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Reason") & "</td>")
                                            Response_WriteLine("<td align=""right"" nowrap>" & sqlDataReader.Item("Msg_Dt") & "</td>")
                                            Response_WriteLine("<td align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("Msg_Tm"), False) & "</td>")
                                            If MCompleted = "Yes" Then
                                                Response_WriteLine("<td>Yes</td>")
                                                Response_WriteLine("<td align=""right"" nowrap>" & Me.roundClock(Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "BH")) & "</td>")
                                            Else
                                                Response_WriteLine("<td>&nbsp;</td>")
                                                Response_WriteLine("<td>&nbsp;</td>")
                                            End If
                                            Response_WriteLine("<td nowrap>" & "<b><font color=""red"">Created By </font></b>" & AssignedName & "</td>")
                                            Response_WriteLine("</tr>")
                                            lastIndex = sqlDataReader.Item("Msg_Index")
                                        End If


                                        ' now show the Flag Details in its own row in the same shading
                                        ' -- sample tab_Audit.Au_Detail --
                                        ' Flagged by VHA12\vhachsPaulP
                                        ' garrett.knapp@va.gov
                                        ' jeffrey.bott@va.gov
                                        ' john.provenzano@va.gov
                                        ' diane.mathews@va.gov
                                        ' pt. belongs to GM-6 not 3 and has already been taken care of by them

                                        ' just pull out the last portion after the email addresses
                                        flagMSG = sqlDataReader.Item("Au_Detail")
                                        flagMSG = Replace(flagMSG, vbCrLf, " ")
                                        flagArray = Nothing
                                        flagArray = Split(flagMSG, "@va.gov ")
                                        flagUBound = UBound(flagArray)
                                        If flagUBound = 0 Then
                                            flagMSG = sqlDataReader.Item("Au_Detail")
                                        Else
                                            flagMSG = flagArray(flagUBound)
                                            If flagMSG = "" Then
                                                flagMSG = sqlDataReader.Item("Au_Detail")
                                            End If
                                        End If

                                        MAssigned = sqlDataReader.Item("Au_Username")
                                        If IsDBNull(MAssigned) Then
                                            MAssigned = ""
                                        Else
                                            MAssigned = Me.GetMemberNameFlaggedUandTI(MAssigned, sqlDataReader.Item("Msg_TeamIndex"))
                                            If MAssigned = "" Then
                                                MAssigned = Me.CleanUserName(sqlDataReader.Item("Au_Username")) & " - " & Me.PollMemberNameForLogin(sqlDataReader.Item("Au_Username"))
                                            End If
                                        End If
                                        If MAssigned = "" Then
                                            MAssigned = "&nbsp;"
                                        End If
                                        Response_WriteLine("<tr bgcolor=""" & color & """ valign=""top""><td>&nbsp;</td>")
                                        Response_WriteLine("<td colspan=""3"" width=""420"">" & flagMSG & "</td>")
                                        Response_WriteLine("<td nowrap>" & sqlDataReader.Item("Au_Dt") & "</td>")
                                        Response_WriteLine("<td align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("Au_Tm"), False) & "</td>")
                                        Response_WriteLine("<td colspan=""3"" nowrap><b><font color=""red"">Flagged by </font></b>" & MAssigned & "</td>")
                                        Response_WriteLine("</tr>")
                                    End While
                                    Response_WriteLine("<tr><td colspan=""9""><center>Showing records " & Start & " through " & Finish & " = " & ctr & " Messages in " & Me.SiteName & ".</center></td></tr>")
                                    Response_WriteLine("</tbody></table>")
                                    Response_WriteLine("</td></tr></table>")
                                    Response_WriteLine("</p></div></div>")
                                    Response.Write(navBar)
                                    Response_WriteLine("<p><b>BH</b> = time elapsed in Business Hours (8a-5p) between creation and closure of Message.</p>")
                                End If

                            End If ' err.number <> 0

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If ' Max = 0

                Case "Reports"
                    ' ---
                    ' Reports
                    ' ---
                    Dim ReportType, form_TeamSelect, form_StartDate, form_EndDate, flipdate, rsDate
                    Dim selectArray, selectItem, selectName
                    ReportType = Request.Form("ReportType")
                    form_TeamSelect = Request.Form("form_TeamSelect")
                    form_StartDate = Request.Form("form_StartDate")
                    form_EndDate = Request.Form("form_EndDate")
                    ' form_TeamSelect
                    '   either 
                    '	  "All"
                    '	  "PACT", "FEE", *** one of the values within tab_Reasons.ReType
                    '	  "10, 15, 20" or "12" etc.
                    '   points to TeamIndex

                    If form_TeamSelect = "" And ReportType <> "" Then
                        Response_WriteLine("<p>No Teams selected, defaulting to All Teams</p>")
                        form_TeamSelect = "All"
                    End If

                    ' strip off situation when user selects "blank" and something else
                    If Left(form_TeamSelect, 1) = "," Then
                        form_TeamSelect = Right(form_TeamSelect, Len(form_TeamSelect) - 1)
                    End If
                    If form_TeamSelect = "All" Then
                        ' All - don't limit to Type
                        RType = "All"
                    Else
                        If IsNumeric(form_TeamSelect) And InStr(form_TeamSelect, ",") = 0 Then
                            ' single Team, Max is limited to just this Type
                            RType = Me.GetTypeFromTeamIndex(form_TeamSelect)
                        Else
                            If InStr(form_TeamSelect, ",") Then
                                ' multiple Indexes selected
                                RType = "Multiple"
                            Else
                                ' one of the Reason Types is selected
                                RType = form_TeamSelect
                            End If
                        End If
                    End If

                    ' First make sure a Type (or All) and Specific Team weren't both chosen.
                    If RType = "Multiple" Then
                        ' multiple Indexes selected, all must be Numeric
                        selectArray = Split(form_TeamSelect & ",zzz", ",")
                        selectItem = 0
                        Do While selectArray(selectItem) <> "zzz"
                            If Not IsNumeric(selectArray(selectItem)) Then
                                RType = "Error"
                            End If
                            selectItem = selectItem + 1
                        Loop
                    End If

                    If form_StartDate = "" Or Not IsDate(form_StartDate) Then
                        form_StartDate = DateAdd("m", -1, theDate).ToShortDateString
                        If ReportType <> "" And ReportType <> "Average Delays" Then
                            ' this form value is blank by default, only show error if submitted to run a report
                            Response_WriteLine("<p><font color=""red"">Bad Start Date, defaulting to " & form_StartDate & "</font></p>")
                        End If
                    Else
                        form_StartDate = CDate(form_StartDate).ToShortDateString
                    End If
                    If form_EndDate = "" Or Not IsDate(form_EndDate) Then
                        form_EndDate = theDate.ToShortDateString
                        If ReportType <> "" And ReportType <> "Average Delays" Then
                            ' this form value is blank by default, only show error if submitted to run a report
                            Response_WriteLine("<p><font color=""red"">Bad End Date, defaulting to " & form_EndDate & "</font></p>")
                        End If
                    Else
                        form_EndDate = CDate(form_EndDate).ToShortDateString
                    End If
                    If DateDiff("d", form_StartDate, form_EndDate) < 0 Then
                        ' flipped, correct them
                        flipdate = form_StartDate
                        form_StartDate = form_EndDate
                        form_EndDate = flipdate
                    End If

                    ' variables used in multiple ReportTypes
                    Dim cntMore, cntTotal, perMore, perTotal
                    Dim MaxDelay, LongDelayList
                    Dim thisDelay

                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    Select Case ReportType

                        Case "Completion Rate in Hours"

                            If RType = "Error" Then
                                Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" with anything else.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and narrow down the selection</font></p>")
                            Else

                                Dim cntThirty, cntSixty, cntTwoHours, cntThreeHours, cntFourHours
                                Dim perThirty, perSixty, perTwoHours, perThreeHours, perFourHours

                                form_CheckSuppressDetails = Request.Form("form_SuppressDetails")

                                cntThirty = 0
                                cntSixty = 0
                                cntTwoHours = 0
                                cntThreeHours = 0
                                cntFourHours = 0
                                cntMore = 0
                                cntTotal = 0
                                MaxDelay = 0
                                LongDelayList = ""

                                ' FOR LOOPS TO BUILD COUNTS
                                sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_LocationIndex, tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Reason," & " tab_Audit.Au_IndexMessage, tab_Messages.Msg_LastName," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm, tab_Audit.Au_Username" & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index"
                                ' #date# for access, 'date' for sSqlString
                                If _clsMessageVAR.BUsesSqlString = True Then
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= '" & form_StartDate & "' AND tab_Messages.Msg_Dt <= '" & form_EndDate & "'"
                                Else
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= #" & form_StartDate & "# AND tab_Messages.Msg_Dt <= #" & form_EndDate & "#"
                                End If
                                sSqlString = sSqlString & " AND tab_Audit.Au_Action = 'Completed' AND tab_Messages.Msg_SiteNum = '" & S & "'"

                                If RType = "All" Then
                                    ' all teams
                                    selectName = "Site: " & Me.GetSiteName(S)
                                Else
                                    If RType = "Multiple" Then
                                        ' multiple chosen
                                        selectArray = Split(form_TeamSelect & ",zzz", ",")
                                        selectItem = 0
                                        selectName = "Teams: "
                                        sSqlString = sSqlString & " AND ("
                                        Do While selectArray(selectItem) <> "zzz"
                                            If selectItem = 0 Then
                                                sSqlString = sSqlString & "tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                selectName = selectName & Me.GetTeamName(selectArray(selectItem))
                                            Else
                                                sSqlString = sSqlString & " OR tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                selectName = selectName & ", " & Me.GetTeamName(selectArray(selectItem))
                                            End If
                                            selectItem = selectItem + 1
                                        Loop
                                        sSqlString = sSqlString & ")"
                                    Else
                                        ' here RType is the Reason Type for one of the teams
                                        If IsNumeric(form_TeamSelect) And InStr(form_TeamSelect, ",") = 0 Then
                                            ' single Team
                                            sSqlString = sSqlString & " AND tab_Messages.Msg_TeamIndex = " & form_TeamSelect
                                            selectName = "Team: " & Me.GetTeamName(form_TeamSelect)
                                        Else
                                            ' one of the Reason Types chosen
                                            selectName = "All " & RType & " Teams"
                                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                                        End If
                                    End If
                                End If
                                ' if multiple "Completed" audits, then put the first completion first
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt ASC, tab_Audit.Au_Tm ASC;"

                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                'On Error Resume Next

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Err.Number <> 0 Then
                                        Response.Write("<p>A server error occurred. Unable to load the Report at this time, try again later.</p>")
                                        Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                        'On Error GoTo 0
                                    Else

                                        If Not sqlDataReader.HasRows Then
                                            Response_WriteLine("<p>No Messages found for the range specified.  Click <A HREF=""javascript:history.back()"">Back</A> and try again.</p>")
                                        Else
                                            lastIndex = 0
                                            While sqlDataReader.Read = True
                                                If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                                    ' same message, skip it:
                                                    'Response.Write("skipping " & sqlDataReader.Item("Msg_Index") & ", it has multiple Completions<br>")
                                                Else
                                                    ' new message, check it:
                                                    lastIndex = sqlDataReader.Item("Msg_Index")

                                                    ' returns decimal business hours
                                                    thisDelay = Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "BH")

                                                    If thisDelay >= 0 And thisDelay < 0.5 Then
                                                        cntThirty = cntThirty + 1
                                                    End If
                                                    If thisDelay >= 0.5 And thisDelay < 1 Then
                                                        cntSixty = cntSixty + 1
                                                    End If
                                                    If thisDelay >= 1 And thisDelay < 2 Then
                                                        cntTwoHours = cntTwoHours + 1
                                                    End If
                                                    If thisDelay >= 2 And thisDelay < 3 Then
                                                        cntThreeHours = cntThreeHours + 1
                                                    End If
                                                    If thisDelay >= 3 And thisDelay < 4 Then
                                                        cntFourHours = cntFourHours + 1
                                                    End If
                                                    If thisDelay >= 4 Then
                                                        cntMore = cntMore + 1
                                                    End If
                                                    If thisDelay > MaxDelay Then
                                                        MaxDelay = thisDelay
                                                    End If
                                                    If thisDelay > 2 And IsNothing(form_CheckSuppressDetails) Then
                                                        If IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                                            LongDelayList = LongDelayList & "<tr><td>&nbsp;</td>"
                                                        Else
                                                            LongDelayList = LongDelayList & "<tr><td>" & sqlDataReader.Item("Msg_LastName") & "</td>"
                                                        End If
                                                        rsDate = sqlDataReader.Item("Msg_Dt")
                                                        'flip sSqlString date format to vbscript date format
                                                        rsDate = CDate(rsDate)
                                                        LongDelayList = LongDelayList & "<td>" & rsDate & "</td>" & "<td>" & sqlDataReader.Item("Msg_Reason") & "</td>" & "<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & lastIndex & """>" & lastIndex & "</a></td></tr>" & vbCrLf
                                                    End If
                                                    cntTotal = cntTotal + 1
                                                End If
                                            End While

                                            If cntThirty = 0 Then
                                                perThirty = 0
                                            Else
                                                perThirty = 100 * cntThirty / cntTotal
                                            End If
                                            If cntSixty = 0 Then
                                                perSixty = 0
                                            Else
                                                perSixty = 100 * cntSixty / cntTotal
                                            End If
                                            If cntTwoHours = 0 Then
                                                perTwoHours = 0
                                            Else
                                                perTwoHours = 100 * cntTwoHours / cntTotal
                                            End If
                                            If cntThreeHours = 0 Then
                                                perThreeHours = 0
                                            Else
                                                perThreeHours = 100 * cntThreeHours / cntTotal
                                            End If
                                            If cntFourHours = 0 Then
                                                perFourHours = 0
                                            Else
                                                perFourHours = 100 * cntFourHours / cntTotal
                                            End If
                                            If cntMore = 0 Then
                                                perMore = 0
                                            Else
                                                perMore = 100 * cntMore / cntTotal
                                            End If
                                            If cntTotal = 0 Then
                                                perTotal = 0
                                            Else
                                                perTotal = 100 * cntTotal / cntTotal
                                            End If

                                            If LongDelayList = "" And form_CheckSuppressDetails = "on" Then
                                                LongDelayList = "<tr><td colspan=""3""><font color=""green"">Records Output Suppressed</font></td></tr>"
                                            End If
                                            If LongDelayList = "" And IsNothing(form_CheckSuppressDetails) Then
                                                LongDelayList = "<tr><td colspan=""3"">None Found</td></tr>"
                                            End If
                                            Response_WriteLine("<div id=Grid style=""font-family:Arial""><p><table border=""1"" cellspacing=""0"" style=""width:30%;"">")
                                            Response_WriteLine("<tr><th colspan=""4"">Completion Rate In Business Hours (8a-5p) for Closed Messages</th></tr>")
                                            Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">" & selectName & "</th></tr>")
                                            Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">Range: " & form_StartDate & "-" & form_EndDate & "</th></tr></table>")
                                            Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"" style=""width:30%;""><tr><th>&nbsp;&nbsp;Time</th><th>&nbsp;&nbsp;Count</th><th align=""right"">&nbsp;&nbsp;&nbsp;%</th><th>Cumul.%</th></tr>")
                                            Response_WriteLine("<tr><td>&lt; 30 Minutes</td><td align=""right"">" & cntThirty & "</td><td align=""right"">" & Me.roundit(perThirty, 0) & "%</td><td align=""right"">" & Me.roundit(perThirty, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>31 to 60 Minutes</td><td align=""right"">" & cntSixty & "</td><td align=""right"">" & Me.roundit(perSixty, 0) & "%</td><td align=""right"">" & Me.roundit(perThirty + perSixty, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>1 Hour to 2 Hours</td><td align=""right"">" & cntTwoHours & "</td><td align=""right"">" & Me.roundit(perTwoHours, 0) & "%</td><td align=""right"">" & Me.roundit(perThirty + perSixty + perTwoHours, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>2 Hours to 3 Hours</td><td align=""right"">" & cntThreeHours & "</td><td align=""right"">" & Me.roundit(perThreeHours, 0) & "%</td><td align=""right"">" & Me.roundit(perThirty + perSixty + perTwoHours + perThreeHours, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>3 Hours to 4 Hours</td><td align=""right"">" & cntFourHours & "</td><td align=""right"">" & Me.roundit(perFourHours, 0) & "%</td><td align=""right"">" & Me.roundit(perThirty + perSixty + perTwoHours + perThreeHours + perFourHours, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>&gt; 4 hours</td><td align=""right"">" & cntMore & "</td><td align=""right"">" & Me.roundit(perMore, 0) & "%</td><td align=""right"">" & Me.roundit(perThirty + perSixty + perTwoHours + perThreeHours + perFourHours + perMore, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>&nbsp;</td><td align=""right"">" & cntTotal & "</td><td align=""right"">" & Me.roundit(perTotal, 0) & "%</td><td>&nbsp;</td></tr>")
                                            Response_WriteLine("<tr><td>Greatest Delay</td><td align=""right"">" & Me.roundit(MaxDelay, 0) & "</td><td>Hours</td><td>&nbsp;</td></tr>")
                                            Response_WriteLine("</table></p></div>")
                                            Response_WriteLine("<p><input type=""button"" id=""btnExport"" Class=""btn btn-primary"" value=""Export To PDF"" onclick=""javascript:exportReportCRHours()""></p>")
                                            Response_WriteLine("<p><table><tr><td colspan=""4""><b>Messages Completed After 2 Hour Deadline</b></td></tr>")
                                            Response_WriteLine("<tr><td><b>Patient</b></td><td><b>Date</b></td><td>Reason</td><td>Index</td></tr>")
                                            Response_WriteLine("" & LongDelayList & "")
                                            Response_WriteLine("</table></p>")
                                        End If

                                    End If ' err.number <> 0

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                            End If ' RType = "Error"

                        Case "Completion Rate in DaysC"

                            If RType = "Error" Then
                                Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" with anything else.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and narrow down the selection</font></p>")
                            Else

                                Dim cntZeroDay, cntOneDay, cntTwoDays, cntThreeDays
                                Dim perZeroDay, perOneDay, perTwoDays, perThreeDays

                                form_CheckSuppressDetails = Request.Form("form_SuppressDetails")

                                cntZeroDay = 0
                                cntOneDay = 0
                                cntTwoDays = 0
                                cntThreeDays = 0
                                cntMore = 0
                                cntTotal = 0
                                MaxDelay = 0
                                LongDelayList = ""

                                ' FOR LOOPS TO BUILD COUNTS
                                sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_LocationIndex, tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Reason," & " tab_Audit.Au_IndexMessage, tab_Messages.Msg_LastName," & " tab_Messages.Msg_Dt, tab_Messages.Msg_Tm, tab_Audit.Au_Dt, tab_Audit.Au_Tm, tab_Audit.Au_Username" & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index"
                                ' #date# for access, 'date' for sSqlString
                                If _clsMessageVAR.BUsesSqlString = True Then
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= '" & form_StartDate & "' AND tab_Messages.Msg_Dt <= '" & form_EndDate & "'"
                                Else
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= #" & form_StartDate & "# AND tab_Messages.Msg_Dt <= #" & form_EndDate & "#"
                                End If
                                sSqlString = sSqlString & " AND tab_Audit.Au_Action = 'Completed' AND tab_Messages.Msg_SiteNum = '" & S & "'"

                                If RType = "All" Then
                                    ' all teams
                                    selectName = "Site: " & Me.GetSiteName(S)
                                Else
                                    If RType = "Multiple" Then
                                        ' multiple chosen
                                        selectArray = Split(form_TeamSelect & ",zzz", ",")
                                        selectItem = 0
                                        selectName = "Teams: "
                                        sSqlString = sSqlString & " AND ("
                                        Do While selectArray(selectItem) <> "zzz"
                                            If selectItem = 0 Then
                                                sSqlString = sSqlString & "tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                selectName = selectName & Me.GetTeamName(selectArray(selectItem))
                                            Else
                                                sSqlString = sSqlString & " OR tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                selectName = selectName & ", " & Me.GetTeamName(selectArray(selectItem))
                                            End If
                                            selectItem = selectItem + 1
                                        Loop
                                        sSqlString = sSqlString & ")"
                                    Else
                                        ' here RType is the Reason Type for one of the teams
                                        If IsNumeric(form_TeamSelect) And InStr(form_TeamSelect, ",") = 0 Then
                                            ' single Team
                                            sSqlString = sSqlString & " AND tab_Messages.Msg_TeamIndex = " & form_TeamSelect
                                            selectName = "Team: " & Me.GetTeamName(form_TeamSelect)
                                        Else
                                            ' one of the Reason Types chosen
                                            selectName = "All " & RType & " Teams"
                                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                                        End If
                                    End If
                                End If
                                ' if multiple "Completed" audits, then put the first completion first
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC, tab_Audit.Au_Dt ASC, tab_Audit.Au_Tm ASC;"

                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                'On Error Resume Next

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Err.Number <> 0 Then
                                        Response.Write("<p>A server error occurred. Unable to load the Report at this time, try again later.</p>")
                                        Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                        'On Error GoTo 0
                                    Else

                                        If Not sqlDataReader.HasRows Then
                                            Response_WriteLine("<p>No Messages found for the range specified.  Click <A HREF=""javascript:history.back()"">Back</A> and try again.</p>")
                                        Else
                                            ' lastIndex would be the same if Audit has multiple "tab_Audit.Au_Action=Completed" entries
                                            lastIndex = 0
                                            While sqlDataReader.Read = True
                                                If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                                    ' same message, skip it:
                                                    'Response.Write("skipping " & sqlDataReader.Item("Msg_Index") & ", it has multiple Completions<br>")
                                                Else
                                                    ' new message, check it:
                                                    lastIndex = sqlDataReader.Item("Msg_Index")

                                                    ' returns integer WeekDays
                                                    thisDelay = Me.ComputeDelay(sqlDataReader.Item("Msg_Dt"), sqlDataReader.Item("Msg_Tm"), sqlDataReader.Item("Au_Dt"), sqlDataReader.Item("Au_Tm"), "Weekdays")

                                                    If thisDelay = 0 Then
                                                        cntZeroDay = cntZeroDay + 1
                                                    End If
                                                    If thisDelay = 1 Then
                                                        cntOneDay = cntOneDay + 1
                                                    End If
                                                    If thisDelay = 2 Then
                                                        cntTwoDays = cntTwoDays + 1
                                                    End If
                                                    If thisDelay = 3 Then
                                                        cntThreeDays = cntThreeDays + 1
                                                    End If
                                                    If thisDelay > 3 Then
                                                        cntMore = cntMore + 1
                                                    End If
                                                    If thisDelay > MaxDelay Then
                                                        MaxDelay = thisDelay
                                                    End If
                                                    If thisDelay > 2 And IsNothing(form_CheckSuppressDetails) Then
                                                        If IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                                            LongDelayList = LongDelayList & "<tr><td>&nbsp;</td>"
                                                        Else
                                                            LongDelayList = LongDelayList & "<tr><td>" & sqlDataReader.Item("Msg_LastName") & "</td>"
                                                        End If
                                                        rsDate = sqlDataReader.Item("Msg_Dt")
                                                        'flip sSqlString date format to vbscript date format
                                                        rsDate = CDate(rsDate)
                                                        LongDelayList = LongDelayList & "<td>" & rsDate & "</td>" & "<td>" & sqlDataReader.Item("Msg_Reason") & "</td>" & "<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & "&I=" & lastIndex & """>" & lastIndex & "</a></td></tr>" & vbCrLf
                                                    End If
                                                    cntTotal = cntTotal + 1
                                                End If
                                            End While

                                            If cntZeroDay = 0 Then
                                                perZeroDay = 0
                                            Else
                                                perZeroDay = 100 * cntZeroDay / cntTotal
                                            End If
                                            If cntOneDay = 0 Then
                                                perOneDay = 0
                                            Else
                                                perOneDay = 100 * cntOneDay / cntTotal
                                            End If
                                            If cntTwoDays = 0 Then
                                                perTwoDays = 0
                                            Else
                                                perTwoDays = 100 * cntTwoDays / cntTotal
                                            End If
                                            If cntThreeDays = 0 Then
                                                perThreeDays = 0
                                            Else
                                                perThreeDays = 100 * cntThreeDays / cntTotal
                                            End If
                                            If cntMore = 0 Then
                                                perMore = 0
                                            Else
                                                perMore = 100 * cntMore / cntTotal
                                            End If
                                            If cntTotal = 0 Then
                                                perTotal = 0
                                            Else
                                                perTotal = 100 * cntTotal / cntTotal
                                            End If

                                            If LongDelayList = "" And form_CheckSuppressDetails = "on" Then
                                                LongDelayList = "<tr><td colspan=""3""><font color=""green"">Records Output Suppressed</font></td></tr>"
                                            End If
                                            If LongDelayList = "" And IsNothing(form_CheckSuppressDetails) Then
                                                LongDelayList = "<tr><td colspan=""3"">None Found</td></tr>"
                                            End If
                                            Response_WriteLine("<div id=Grid style=""font-family:Arial""><p><table border=""1"" cellspacing=""0"" style=""width:30%;"">")
                                            Response_WriteLine("<tr><th colspan=""4"">Completion Rate In Weekdays for Closed Messages (Consolidated)</th></tr>")
                                            Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">" & selectName & "</th></tr>")
                                            Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">Range: " & form_StartDate & "-" & form_EndDate & "</th></tr></table>")
                                            Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"" style=""width:30%;""><tr><th>&nbsp;&nbsp;Time</th><th>&nbsp;&nbsp;Count</th><th align=""right"">&nbsp;&nbsp;&nbsp;%</th><th>Cumul.%</th></tr>")
                                            Response_WriteLine("<tr><td>0 days</td><td align=""right"">" & cntZeroDay & "</td><td align=""right"">" & Me.roundit(perZeroDay, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>1 day</td><td align=""right"">" & cntOneDay & "</td><td align=""right"">" & Me.roundit(perOneDay, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>2 days</td><td align=""right"">" & cntTwoDays & "</td><td align=""right"">" & Me.roundit(perTwoDays, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay + perTwoDays, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>3 days</td><td align=""right"">" & cntThreeDays & "</td><td align=""right"">" & Me.roundit(perThreeDays, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay + perTwoDays + perThreeDays, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>&gt; 3 days</td><td align=""right"">" & cntMore & "</td><td align=""right"">" & Me.roundit(perMore, 0) & "%</td><td align=""right"">" & Me.roundit(perZeroDay + perOneDay + perTwoDays + perThreeDays + perMore, 0) & "%</td></tr>")
                                            Response_WriteLine("<tr><td>&nbsp;</td><td align=""right"">" & cntTotal & "</td><td align=""right"">" & Me.roundit(perTotal, 0) & "%</td><td>&nbsp;</td></tr>")
                                            Response_WriteLine("<tr><td>Greatest Delay</td><td align=""right"">" & Me.roundit(MaxDelay, 1) & "</td><td>Days</td><td>&nbsp;</td></tr>")
                                            Response_WriteLine("</table></p></div>")
                                            Response_WriteLine("<p><input type=""button"" id=""btnExport"" Class=""btn btn-primary"" value=""Export To PDF"" onclick=""javascript:exportReportCRWeekdaysC()""></p>")
                                            Response_WriteLine("<p><table><tr><td colspan=""4""><b>Messages Completed After 2 Day Deadline</b></td></tr>")
                                            Response_WriteLine("<tr><td><b>Patient</b></td><td><b>Date</b></td><td>Reason</td><td>Index</td></tr>")
                                            Response_WriteLine("" & LongDelayList & "")
                                            Response_WriteLine("</table></p>")
                                        End If

                                    End If ' err.number <> 0

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                            End If ' RType = "Error"

                        Case "Completion Rate in DaysI"

                            If RType = "Error" Then
                                Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" with anything else.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and narrow down the selection</font></p>")
                            Else
                                selectArray = Split(form_TeamSelect & ",zzz", ",")
                                selectItem = 0

                                If RType = "All" Then
                                    Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" for this report.<br>")
                                    Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and please select either single Team or multiple Teams (by holding CTRL or SHIFT while selecting).</font></p>")
                                Else
                                    Response_WriteLine("<p><input type=""button"" id=""btnExport"" Class=""btn btn-primary"" value=""Export To PDF"" onclick=""javascript:exportReportCRWeekdaysI()""></p>")
                                    Response_WriteLine("<p><font color=""green""><small>Note: Report data can be copy/pasted to Excel if so desired</small></font></p>")
                                    Response_WriteLine("<div id=Grid style=""font-family:Arial"">")
                                    Do While selectArray(selectItem) <> "zzz"
                                        CalculateAndWriteTeamDelays(selectArray(selectItem))
                                        selectItem = selectItem + 1
                                    Loop
                                    Response_WriteLine("</div>")
                                    Response_WriteLine("<p><input type=""button"" id=""btnExport"" Class=""btn btn-primary"" value=""Export To PDF"" onclick=""javascript:exportReportCRWeekdaysI()""></p>")
                                End If
                            End If ' RType = "Error"

                        Case "Message Totals"

                            If RType = "Error" Then
                                Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" with anything else.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and narrow down the selection</font></p>")
                            Else

                                Dim VHTotal, VHOpen, VHClosed, VHAssigned, nFirstRecord
                                Dim VHDate, VHLastDate
                                Dim colDateTotal, colTotalTotal, colOpenTotal, colClosedTotal, colAssignedTotal

                                ' FOR LOOPS TO BUILD COUNTS
                                sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Assigned, tab_Messages.Msg_Dt" & " FROM tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index"
                                ' #date# for access, 'date' for sSqlString
                                If _clsMessageVAR.BUsesSqlString = True Then
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= '" & form_StartDate & "' AND tab_Messages.Msg_Dt <= '" & form_EndDate & "'"
                                Else
                                    sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= #" & form_StartDate & "# AND tab_Messages.Msg_Dt <= #" & form_EndDate & "#"
                                End If
                                sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "'"

                                If RType = "All" Then
                                    ' all teams
                                    selectName = "Site: " & Me.GetSiteName(S)
                                Else
                                    If RType = "Multiple" Then
                                        ' multiple chosen
                                        selectArray = Split(form_TeamSelect & ",zzz", ",")
                                        selectItem = 0
                                        selectName = "Teams: "
                                        sSqlString = sSqlString & " AND ("
                                        Do While selectArray(selectItem) <> "zzz"
                                            If selectItem = 0 Then
                                                sSqlString = sSqlString & "tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                selectName = selectName & Me.GetTeamName(selectArray(selectItem))
                                            Else
                                                sSqlString = sSqlString & " OR tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                selectName = selectName & ", " & Me.GetTeamName(selectArray(selectItem))
                                            End If
                                            selectItem = selectItem + 1
                                        Loop
                                        sSqlString = sSqlString & ")"
                                    Else
                                        ' here RType is the Reason Type for one of the teams
                                        If IsNumeric(form_TeamSelect) And InStr(form_TeamSelect, ",") = 0 Then
                                            ' single Team
                                            sSqlString = sSqlString & " AND tab_Messages.Msg_TeamIndex = " & form_TeamSelect
                                            selectName = "Team: " & Me.GetTeamName(form_TeamSelect)
                                        Else
                                            ' one of the Reason Types chosen
                                            selectName = "All " & RType & " Teams"
                                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                                        End If
                                    End If
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"

                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                'On Error Resume Next

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Err.Number <> 0 Then
                                        Response.Write("<p>A server error occurred. Unable to load the Report at this time, try again later.</p>")
                                        Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                        'On Error GoTo 0
                                    Else

                                        If Not sqlDataReader.HasRows Then
                                            Response_WriteLine("<p>No Messages found for the range specified.  Click <A HREF=""javascript:history.back()"">Back</A> and try again.</p>")
                                        Else
                                            VHTotal = 0
                                            VHOpen = 0
                                            VHClosed = 0
                                            VHAssigned = 0
                                            colDateTotal = 0
                                            colTotalTotal = 0
                                            colOpenTotal = 0
                                            colClosedTotal = 0
                                            colAssignedTotal = 0
                                            nFirstRecord = 1

                                            Response_WriteLine("<div id=Grid style=""font-family:Arial""><p><table border=""1"" cellspacing=""0"" style=""width:40%;"">")
                                            Response_WriteLine("<tr><th>&nbsp;Message Totals</th></tr>")
                                            Response_WriteLine("<tr><th style=""background-color: #fff;"">Showing Message counts between " & form_StartDate & " and " & form_EndDate & " for " & selectName & ".</th></tr></table>")
                                            Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"" style=""width:40%;"" border=""1"" bordercolor=""black"" cellspacing=""0"">")
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th>Day</th><th>Date</th><th>Total</th><th>Open</th><th>Closed</th><th>Assigned</th></tr>")

                                            While sqlDataReader.Read = True
                                                If nFirstRecord = 1 Then
                                                    nFirstRecord = 0
                                                    VHDate = sqlDataReader.Item("Msg_Dt")
                                                    ' flip sSqlString date format to vbscript date format
                                                    VHDate = CDate(VHDate)
                                                    VHLastDate = VHDate
                                                    rsDate = sqlDataReader.Item("Msg_Dt")

                                                    ' there might be a gap at the beginning if blank days are before form_EndDate
                                                    If DateDiff("d", form_EndDate, VHDate) <> 0 Then
                                                        ' this loop will show a blank for the dates with no Messages
                                                        Do While DateDiff("d", form_EndDate, VHDate) <> 0
                                                            colDateTotal = colDateTotal + 1
                                                            Response_WriteLine("<tr align=""right""><td>" & Me.DayLetter(Weekday(form_EndDate)) & "</td><td>" & form_EndDate & "</td><td>0</td><td>0</td><td>0</td><td>0</td></tr>")
                                                            form_EndDate = DateAdd("d", -1, form_EndDate)
                                                        Loop
                                                    End If
                                                Else
                                                    rsDate = sqlDataReader.Item("Msg_Dt")
                                                End If

                                                ' flip sSqlString date format to vbscript date format
                                                rsDate = CDate(rsDate)
                                                If DateDiff("d", VHDate, rsDate) = 0 Then
                                                    ' same day, do nothing special
                                                Else
                                                    ' this loop will show a blank for the dates with no Messages
                                                    Do While DateDiff("d", VHDate, VHLastDate) > 1
                                                        VHLastDate = DateAdd("d", -1, VHLastDate)
                                                        colDateTotal = colDateTotal + 1
                                                        Response_WriteLine("<tr align=""right""><td>" & Me.DayLetter(Weekday(VHLastDate)) & "</td><td>" & VHLastDate & "</td><td>0</td><td>0</td><td>0</td><td>0</td></tr>")
                                                    Loop
                                                    ' new date.  Write the previous day's output and reset the counters
                                                    Response_WriteLine("<tr align=""right""><td>" & Me.DayLetter(Weekday(VHDate)) & "</td><td>" & VHDate & "</td><td bgcolor=""#eeeeee"">" & VHTotal & "</td>")
                                                    If VHClosed = VHTotal Then
                                                        Response_WriteLine("<td bgcolor=""#99CC66"">" & VHOpen & "</td>")
                                                    Else
                                                        Response_WriteLine("<td bgcolor=""#FF9966"">" & VHOpen & "</td>")
                                                    End If
                                                    Response_WriteLine("<td>" & VHClosed & "</td><td>" & VHAssigned & "</td></tr>")
                                                    ' tally up the column counters
                                                    colDateTotal = colDateTotal + 1
                                                    colTotalTotal = colTotalTotal + VHTotal
                                                    colOpenTotal = colOpenTotal + VHOpen
                                                    colClosedTotal = colClosedTotal + VHClosed
                                                    colAssignedTotal = colAssignedTotal + VHAssigned
                                                    ' reset the row counters
                                                    VHLastDate = VHDate
                                                    VHDate = rsDate
                                                    VHTotal = 0
                                                    VHOpen = 0
                                                    VHClosed = 0
                                                    VHAssigned = 0
                                                End If
                                                VHTotal = VHTotal + 1
                                                If Not IsDBNull(sqlDataReader.Item("Msg_Completed")) Then
                                                    If sqlDataReader.Item("Msg_Completed") = "Yes" Then
                                                        VHClosed = VHClosed + 1
                                                    Else
                                                        VHOpen = VHOpen + 1
                                                    End If
                                                Else
                                                    VHOpen = VHOpen + 1
                                                End If
                                                If Not IsDBNull(sqlDataReader.Item("Msg_Assigned")) Then
                                                    VHAssigned = VHAssigned + 1
                                                End If
                                            End While

                                            ' display the last day that didn't get shown in the loop
                                            ' this loop will show a blank for the dates with no Messages
                                            Do While DateDiff("d", VHDate, VHLastDate) > 1
                                                VHLastDate = DateAdd("d", -1, VHLastDate)
                                                colDateTotal = colDateTotal + 1
                                                Response_WriteLine("<tr align=""right""><td>" & Me.DayLetter(Weekday(VHLastDate)) & "</td><td>" & VHLastDate & "</td><td>0</td><td>0</td><td>0</td><td>0</td></tr>")
                                            Loop
                                            Response_WriteLine("<tr align=""right""><td>" & Me.DayLetter(Weekday(VHDate)) & "</td><td>" & VHDate & "</td><td bgcolor=""#eeeeee"">" & VHTotal & "</td>")
                                            If VHClosed = VHTotal Then
                                                Response_WriteLine("<td bgcolor=""#99CC66"">" & VHOpen & "</td>")
                                            Else
                                                Response_WriteLine("<td bgcolor=""#FF9966"">" & VHOpen & "</td>")
                                            End If
                                            Response_WriteLine("<td>" & VHClosed & "</td><td>" & VHAssigned & "</td></tr>")
                                            ' now change the last shown date value
                                            VHLastDate = VHDate
                                            ' tally up the column counters
                                            colDateTotal = colDateTotal + 1
                                            colTotalTotal = colTotalTotal + VHTotal
                                            colOpenTotal = colOpenTotal + VHOpen
                                            colClosedTotal = colClosedTotal + VHClosed
                                            colAssignedTotal = colAssignedTotal + VHAssigned

                                            ' there is a gap at the end if blank days are at the end
                                            If DateDiff("d", form_StartDate, VHDate) <> 0 Then
                                                ' this loop will show a blank for the dates with no Messages
                                                Do While DateDiff("d", form_StartDate, VHDate) <> 0
                                                    VHDate = DateAdd("d", -1, VHDate)
                                                    colDateTotal = colDateTotal + 1
                                                    Response_WriteLine("<tr align=""right""><td>" & Me.DayLetter(Weekday(VHDate)) & "</td><td>" & VHDate & "</td><td>0</td><td>0</td><td>0</td><td>0</td></tr>")
                                                Loop
                                            End If

                                            ' display the column counts
                                            Response_WriteLine("<tr align=""right"" bgcolor=""#d6dbe9"">")
                                            Response_WriteLine("<td>&nbsp;</td>")
                                            Response_WriteLine("<td>" & colDateTotal & " Day(s)" & "</td>")
                                            Response_WriteLine("<td>" & colTotalTotal & "</td>")
                                            Response_WriteLine("<td>" & colOpenTotal & "</td>")
                                            Response_WriteLine("<td>" & colClosedTotal & "</td>")
                                            Response_WriteLine("<td>" & colAssignedTotal & "</td>")
                                            Response_WriteLine("</tr>")
                                            Response_WriteLine("</table></div>")
                                        End If
                                        Response_WriteLine("<p><input type=""button"" id=""btnExport"" Class=""btn btn-primary"" value=""Export To PDF"" onclick=""javascript:exportReportMessageTotals()""></p>")
                                    End If ' err.number <> 0

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                            End If ' RType = "Error"

                        Case "Reason Totals"

                            If RType = "Error" Then
                                Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" with anything else.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and narrow down the selection</font></p>")
                            Else

                                Dim RHDate, RHLastDate
                                Dim RANames(), RATypes(), RAShowType(), RACounts(), RASuperTotals()
                                Dim RMax, RI, RDayTotal, RSuperTotal, Rfound

                                ' GENERATE RMax 
                                ' RMax is the highest index value, not the count of indexes per Reason Type
                                sSqlString = "SELECT MAX(tab_Reasons.Re_Index) AS THECOUNT FROM tab_Reasons WHERE tab_Reasons.Re_Active = 'Yes';"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If sqlDataReader.Read = False Then
                                        RMax = 0
                                    Else
                                        RMax = sqlDataReader.Item("THECOUNT")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                If RMax = 0 Then
                                    Response_WriteLine("<p>Error no Reasons in system</p>")
                                Else
                                    ' initialize the Arrays
                                    ReDim Preserve RANames(RMax)
                                    ReDim Preserve RATypes(RMax)
                                    ReDim Preserve RAShowType(RMax)
                                    ReDim Preserve RACounts(RMax)
                                    ReDim Preserve RASuperTotals(RMax)
                                    For RI = 1 To RMax
                                        RANames(RI) = ""
                                        RATypes(RI) = ""
                                        RAShowType(RI) = ""
                                        RACounts(RI) = 0
                                        RASuperTotals(RI) = 0
                                    Next

                                    ' Fill RANames with the Names
                                    ' and fill RATypes with "On" if the RType matches
                                    sSqlString = "SELECT tab_Reasons.Re_Index, tab_Reasons.Re_Type, tab_Reasons.Re_Name FROM tab_Reasons" & " WHERE tab_Reasons.Re_Active = 'Yes'" & " ORDER BY tab_Reasons.Re_Index;"

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        While sqlDataReader.Read = True
                                            ' Name the Type
                                            RANames(sqlDataReader.Item("Re_Index")) = sqlDataReader.Item("Re_Name")
                                            RATypes(sqlDataReader.Item("Re_Index")) = sqlDataReader.Item("Re_Type")

                                            ' indicate Type is used 
                                            If RType = "All" Then
                                                ' All - don't limit to a type
                                                RAShowType(sqlDataReader.Item("Re_Index")) = "On"
                                            Else
                                                If RType = sqlDataReader.Item("Re_Type") Then
                                                    ' Single Type chosen
                                                    RAShowType(sqlDataReader.Item("Re_Index")) = "On"
                                                Else
                                                    If RType = "Multiple" Then
                                                        ' multiple Indexes selected
                                                        selectArray = Split(form_TeamSelect & ",zzz", ",")
                                                        selectItem = 0
                                                        Do While selectArray(selectItem) <> "zzz"
                                                            If Me.GetTypeFromTeamIndex(selectArray(selectItem)) = sqlDataReader.Item("Re_Type") Then
                                                                RAShowType(sqlDataReader.Item("Re_Index")) = "On"
                                                            End If
                                                            selectItem = selectItem + 1
                                                        Loop
                                                    Else
                                                        ' one of the Reason Types is selected
                                                        ' which does not match the Reason Type for this Re_Index
                                                        ' so leave it off
                                                    End If
                                                End If
                                            End If

                                        End While

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    ' Based on form_TeamSelect:
                                    '	create sSqlString statement to pull counts 
                                    '	fill in value of selectName
                                    sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Completed, tab_Messages.Msg_Assigned, tab_Messages.Msg_Dt, tab_Messages.Msg_Reason, tab_Locations.Lo_Type" & " FROM tab_Messages LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index"
                                    ' #date# for access, 'date' for sSqlString
                                    If _clsMessageVAR.BUsesSqlString = True Then
                                        sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= '" & form_StartDate & "' AND tab_Messages.Msg_Dt <= '" & form_EndDate & "'"
                                    Else
                                        sSqlString = sSqlString & " WHERE tab_Messages.Msg_Dt >= #" & form_StartDate & "# AND tab_Messages.Msg_Dt <= #" & form_EndDate & "#"
                                    End If
                                    sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & S & "'"

                                    If RType = "All" Then
                                        ' all teams
                                        selectName = "Site: " & Me.GetSiteName(S)
                                    Else
                                        If RType = "Multiple" Then
                                            ' multiple chosen
                                            selectArray = Split(form_TeamSelect & ",zzz", ",")
                                            selectItem = 0
                                            selectName = "Teams: "
                                            sSqlString = sSqlString & " AND ("
                                            Do While selectArray(selectItem) <> "zzz"
                                                If selectItem = 0 Then
                                                    sSqlString = sSqlString & "tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                    selectName = selectName & Me.GetTeamName(selectArray(selectItem))
                                                Else
                                                    sSqlString = sSqlString & " OR tab_Messages.Msg_TeamIndex = " & selectArray(selectItem)
                                                    selectName = selectName & ", " & Me.GetTeamName(selectArray(selectItem))
                                                End If
                                                selectItem = selectItem + 1
                                            Loop
                                            sSqlString = sSqlString & ")"
                                        Else
                                            ' here RType is the Reason Type for one of the teams
                                            If IsNumeric(form_TeamSelect) And InStr(form_TeamSelect, ",") = 0 Then
                                                ' single Team
                                                sSqlString = sSqlString & " AND tab_Messages.Msg_TeamIndex = " & form_TeamSelect
                                                selectName = "Team: " & Me.GetTeamName(form_TeamSelect)
                                            Else
                                                ' one of the Reason Types chosen
                                                selectName = "All " & RType & " Teams"
                                                sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & RType & "'"
                                            End If
                                        End If
                                    End If
                                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"

                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    'On Error Resume Next

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If Err.Number <> 0 Then
                                            Response.Write("<p>A server error occurred. Unable to load the Report at this time, try again later.</p>")
                                            Me.ErrorHandler("ERROR: " & Err.Number & "," & Err.Description & ". sSqlString=" & sSqlString, False, False)
                                            'On Error GoTo 0
                                        Else

                                            If sqlDataReader.Read = False Then
                                                Response_WriteLine("<p>No Messages found for the range specified.  Click <A HREF=""javascript:history.back()"">Back</A> and try again.</p>")
                                            Else
                                                RHDate = sqlDataReader.Item("Msg_Dt")
                                                ' flip sSqlString date format to vbscript date format
                                                RHDate = CDate(RHDate)
                                                RHLastDate = RHDate
                                                RDayTotal = 0
                                                RSuperTotal = 0
                                                Response_WriteLine("<div id=Grid style=""font-family:Arial""><p><table border=""1"" cellspacing=""0"" style=""width:90%;"">")
                                                Response_WriteLine("<tr><th>&nbsp;Reason Totals</th></tr>")
                                                Response_WriteLine("<tr><th style=""background-color: #fff;"">Showing Message Reason counts between " & form_StartDate & " and " & form_EndDate & " for " & selectName & ".</th></tr></table><br />")
                                                Response_WriteLine("<table style=""width:90%;"" border=""1"" bordercolor=""black"" cellspacing=""0"">")
                                                Response_WriteLine("<tr bgcolor=""#d6dbe9"" valign=""bottom""><th bgcolor=""#d6dbe9"">Date</th><th bgcolor=""#d6dbe9"">Total</th>")
                                                Response_WriteLine("")
                                                ' display the header row
                                                ' only show those for the appropriate RType, or All
                                                For RI = 1 To RMax
                                                    If RAShowType(RI) = "On" Then
                                                        If RANames(RI) <> "" Then
                                                            Response_WriteLine("<th>" & Replace(RANames(RI), " ", "<br>") & "</th>")
                                                        End If
                                                    End If
                                                Next
                                                Response_WriteLine("</tr>")
                                                ' there might be a gap at the beginning if blank days are before form_EndDate
                                                If DateDiff("d", form_EndDate, VHDate) <> 0 Then
                                                    ' this loop will show a blank for for dates with no Messages
                                                    Do While DateDiff("d", form_EndDate, RHDate) <> 0
                                                        Response_WriteLine("<tr align=""right""><td bgcolor=""#eeeeee"">" & form_EndDate & "</td><td bgcolor=""#eeeeee"">0</td>")
                                                        For RI = 1 To RMax
                                                            If RAShowType(RI) = "On" Then
                                                                If RANames(RI) <> "" Then
                                                                    Response_WriteLine("<td>0</td>")
                                                                End If
                                                            End If
                                                        Next
                                                        Response_WriteLine("</tr>")
                                                        form_EndDate = DateAdd("d", -1, form_EndDate)
                                                    Loop
                                                End If

                                                While sqlDataReader.Read = True
                                                    rsDate = sqlDataReader.Item("Msg_Dt")
                                                    'flip sSqlString date format to vbscript date format
                                                    rsDate = CDate(rsDate)
                                                    If DateDiff("d", RHDate, rsDate) = 0 Then
                                                        ' same day, do nothing special
                                                    Else
                                                        ' NEW DATE
                                                        ' first display the previous date's counters

                                                        ' this loop will show a blank for dates with no Messages
                                                        Do While DateDiff("d", RHDate, RHLastDate) > 1
                                                            RHLastDate = DateAdd("d", -1, RHLastDate)
                                                            Response_WriteLine("<tr align=""right"">")
                                                            Response_WriteLine("<td bgcolor=""#eeeeee"">" & RHLastDate & "</td><td bgcolor=""#eeeeee"">0</td>")
                                                            For RI = 1 To RMax
                                                                If RAShowType(RI) = "On" Then
                                                                    If RANames(RI) <> "" Then
                                                                        Response_WriteLine("<td>0</td>")
                                                                    End If
                                                                End If
                                                            Next
                                                            Response_WriteLine("</tr>")
                                                        Loop

                                                        ' Write the previous day's output
                                                        Response_WriteLine("<tr align=""right"">")
                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">" & RHDate & "</td><td bgcolor=""#eeeeee"">" & RDayTotal & "</td>")
                                                        For RI = 1 To RMax
                                                            If RAShowType(RI) = "On" Then
                                                                If RANames(RI) <> "" Then
                                                                    Response_WriteLine("<td>" & RACounts(RI) & "</td>")
                                                                End If
                                                            End If
                                                        Next
                                                        Response_WriteLine("</tr>")
                                                        ' Reset the daily counts
                                                        'RSuperTotal = RSuperTotal + RDayTotal
                                                        For RI = 1 To RMax
                                                            'RASuperTotals(RI) = RASuperTotals(RI) + RACounts(RI)
                                                            RACounts(RI) = 0
                                                        Next
                                                        RHLastDate = RHDate
                                                        RHDate = sqlDataReader.Item("Msg_Dt")
                                                        ' flip sSqlString date format to vbscript date format
                                                        RHDate = CDate(RHDate)
                                                        RDayTotal = 0

                                                    End If

                                                    ' increment counts
                                                    RSuperTotal = RSuperTotal + 1
                                                    Rfound = False
                                                    For RI = 1 To RMax
                                                        If sqlDataReader.Item("Msg_Reason") = RANames(RI) And sqlDataReader.Item("Lo_Type") = RATypes(RI) Then
                                                            RACounts(RI) = RACounts(RI) + 1
                                                            RDayTotal = RDayTotal + 1
                                                            RASuperTotals(RI) = RASuperTotals(RI) + 1
                                                            Rfound = True
                                                        End If
                                                    Next
                                                    ' if Reason not matched then increment the Other column
                                                    ' this is intended to catch cases where Reasons are turned off but old messages have that reason stamped
                                                    If Rfound = False Then
                                                        For RI = 1 To RMax
                                                            If "Other" = RANames(RI) And sqlDataReader.Item("Lo_Type") = RATypes(RI) Then
                                                                RACounts(RI) = RACounts(RI) + 1
                                                                RDayTotal = RDayTotal + 1
                                                                RASuperTotals(RI) = RASuperTotals(RI) + 1
                                                                Rfound = True
                                                            End If
                                                        Next
                                                    End If

                                                End While

                                                ' display the last day that didn't get shown in the loop
                                                ' this loop will show a blank for for dates with no Messages
                                                Do While DateDiff("d", RHDate, RHLastDate) > 1
                                                    RHLastDate = DateAdd("d", -1, RHLastDate)
                                                    Response_WriteLine("<tr align=""right"">")
                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">" & RHLastDate & "</td><td bgcolor=""#eeeeee"">0</td>")
                                                    For RI = 1 To RMax
                                                        If RAShowType(RI) = "On" Then
                                                            If RANames(RI) <> "" Then
                                                                Response_WriteLine("<td>0</td>")
                                                            End If
                                                        End If
                                                    Next
                                                    Response_WriteLine("</tr>")
                                                Loop
                                                Response_WriteLine("<tr align=""right"">")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">" & RHDate & "</td><td bgcolor=""#eeeeee"">" & RDayTotal & "</td>")
                                                For RI = 1 To RMax
                                                    If RAShowType(RI) = "On" Then
                                                        If RANames(RI) <> "" Then
                                                            Response_WriteLine("<td>" & RACounts(RI) & "</td>")
                                                        End If
                                                    End If
                                                Next
                                                Response_WriteLine("</tr>")
                                                ' now change the last shown date value
                                                RHLastDate = RHDate

                                                ' there is a gap at the end if blank days are at the end
                                                If DateDiff("d", form_StartDate, RHDate) <> 0 Then
                                                    ' this loop will show a blank for for dates with no Messages
                                                    Do While DateDiff("d", form_StartDate, RHDate) <> 0
                                                        RHDate = DateAdd("d", -1, RHDate)
                                                        Response_WriteLine("<tr align=""right"">")
                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">" & RHDate & "</td><td bgcolor=""#eeeeee"">0</td>")
                                                        For RI = 1 To RMax
                                                            If RAShowType(RI) = "On" Then
                                                                If RANames(RI) <> "" Then
                                                                    Response_WriteLine("<td>0</td>")
                                                                End If
                                                            End If
                                                        Next
                                                        Response_WriteLine("</tr>")
                                                    Loop
                                                End If

                                                ' show the totals for the date period
                                                Response_WriteLine("<tr stype=""background-color:#d6dbe9"" align=""right"">")
                                                Response_WriteLine("<td stype=""background-color:#d6dbe9"">Totals</td><td stype=""background-color:#d6dbe9"">" & RSuperTotal & "</td>")
                                                For RI = 1 To RMax
                                                    If RAShowType(RI) = "On" Then
                                                        If RANames(RI) <> "" Then
                                                            Response_WriteLine("<td>" & RASuperTotals(RI) & "</td>")
                                                        End If
                                                    End If
                                                Next
                                                Response_WriteLine("</tr>")
                                                Response_WriteLine("<tr stype=""background-color:#d6dbe9"" align=""right"">")
                                                Response_WriteLine("<td stype=""background-color:#d6dbe9"">Percent</td><td stype=""background-color:#d6dbe9"">100</td>")
                                                For RI = 1 To RMax
                                                    If RAShowType(RI) = "On" Then
                                                        If RANames(RI) <> "" Then
                                                            Response_WriteLine("<td>" & Me.roundit(100 * RASuperTotals(RI) / RSuperTotal, 2) & "</td>")
                                                        End If
                                                    End If
                                                Next
                                                Response_WriteLine("</tr>")
                                                Response_WriteLine("</table></div>")
                                            End If
                                        End If ' err.number <> 0

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End If ' RMax = 0

                            End If ' RType = "Error"

                        Case "Average Delays"

                            If RType = "Error" Then
                                Response_WriteLine("<p><font color=""red"">Selection Error,  cannot select ""-- All --"" with anything else.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and narrow down the selection</font></p>")
                            ElseIf Request.Form("form_ReportReason") = "" Then
                                Response_WriteLine("<p><font color=""red"">Reason type must be selected for this report.<br>")
                                Response_WriteLine("Press <A HREF=""javascript:history.back()"">Back</A> and select Reason from dropdown selection</font></p>")
                            Else

                                Dim ReportReason

                                ReportReason = Request.Form("form_ReportReason")

                                Response_WriteLine("<div id=Grid style=""font-family:Arial""><p><table border=""1"" cellspacing=""0"" style=""width:80%;"">")
                                Response_WriteLine("<tr><th colspan=""4"">Average Delays per Team and Reason</th></tr>")
                                Response_WriteLine("<tr><th colspan=""4"" style=""background-color: #fff;"">" & "Site: " & Me.GetSiteName(S) & "</th></tr></table>")
                                Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"" style=""width:80%;""><tr><th style=""background-color: #fff;"">&nbsp;&nbsp;Team</th><th style=""background-color: #fff;"">&nbsp;&nbsp;Average Delay</th></tr>")

                                If RType = "All" Then
                                    sSqlString = "SELECT tab_Teams.Te_Name, tab_Teams.Te_Index, tab_Teams.Te_Active, tab_Locations.Lo_Name" & " FROM tab_Teams LEFT JOIN tab_Locations" & " ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & S & "'"
                                    sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        While sqlDataReader.Read = True
                                            MSGdelay = Me.ShowReportAverage(sqlDataReader.Item("Te_Index"), ReportReason)
                                            If MSGdelay <> "" Then
                                                Response_WriteLine("<tr valign=""top"">")
                                                Response_WriteLine("<td bgcolor=""#dbe4f0""><b>" & Me.GetTeamName(sqlDataReader.Item("Te_Index")) & "</b></td>")
                                                Response_WriteLine("<td>" & MSGdelay & "</td>")
                                                Response_WriteLine("</tr>")
                                            End If
                                        End While

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try
                                Else
                                    selectArray = Split(form_TeamSelect & ",zzz", ",")
                                    selectItem = 0
                                    If RType = "Multiple" Then
                                        Do While selectArray(selectItem) <> "zzz"
                                            MSGdelay = Me.ShowReportAverage(selectArray(selectItem), ReportReason)
                                            If MSGdelay <> "" Then
                                                Response_WriteLine("<tr valign=""top"">")
                                                Response_WriteLine("<td bgcolor=""#dbe4f0""><b>" & Me.GetTeamName(selectArray(selectItem)) & "</b></td>")
                                                Response_WriteLine("<td>" & MSGdelay & "</td>")
                                                Response_WriteLine("</tr>")
                                            End If
                                            selectItem = selectItem + 1
                                        Loop
                                    Else
                                        MSGdelay = Me.ShowReportAverage(selectArray(selectItem), ReportReason)
                                        If MSGdelay <> "" Then
                                            Response_WriteLine("<tr valign=""top"">")
                                            Response_WriteLine("<td bgcolor=""#dbe4f0""><b>" & Me.GetTeamName(selectArray(selectItem)) & "</b></td>")
                                            Response_WriteLine("<td>" & MSGdelay & "</td>")
                                            Response_WriteLine("</tr>")
                                        End If
                                    End If
                                End If

                                Response_WriteLine("</table></div>")
                                Response_WriteLine("<p><input type=""button"" id=""btnExport"" Class=""btn btn-primary"" value=""Export To PDF"" onclick=""javascript:exportReportReasonTotals()""></p>")

                            End If ' RType = "Error"

                        Case Else

                            ' Reports Menu '

                            If Me.SiteName = "" Then
                                Response_WriteLine("<p>Choose a site to view reports.</p>")
                            Else

                                If form_TeamSelect <> "" Then
                                    ' chose a list of Teams, but didn't pick a report type.  suggest going back so as not to lose the selections
                                    Response_WriteLine("<p>Teams selected but no Report Type chosen.  Click <A HREF=""javascript:history.back()"">Back</A> and try again.</p>")
                                Else
                                    ' Build a Team select box from all Active Teams for this Location
                                    TeamSelect = "<select name=""form_TeamSelect"" multiple size=""10"" class=""form-control""><option selected value=""""></option>" & vbCrLf
                                    If Me.AdminType = "All" Then
                                        TeamSelect = TeamSelect & "<option value=""All"">-- All Teams --</option>" & vbCrLf
                                    End If

                                    ' 2014-4-30 - no longer doing "All PACT" because the PACT style has PACT teams, specialty teams, etc - the meaning doesn't match the LocationType.						
                                    '	' check for "-- All Reasons --"
                                    '	' example:
                                    '	'   "-- All PACT --"
                                    '	'   "-- All FEE --"
                                    '	sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons ORDER BY tab_Reasons.Re_Type;"
                                    '	 rs = db.Execute(sSqlString)
                                    '	if not rs.EOF then
                                    '		do while not rs.EOF
                                    '			if AdminType = "All" or AdminType = sqlDataReader.Item("REASONTYPE") then
                                    '				TeamSelect = TeamSelect & "<option value=""" & sqlDataReader.Item("REASONTYPE") & """>-- All " & sqlDataReader.Item("REASONTYPE") & " Teams --</option>" & VbCrLf
                                    '			end if
                                    '			rs.MoveNext
                                    '		loop
                                    '	end if
                                    '	 rs = nothing
                                    ' 2014-4-30 - end of comment out					

                                    ' add the rest of the Teams (active and inactive)
                                    sSqlString = "SELECT tab_Teams.Te_Name, tab_Teams.Te_Index, tab_Teams.Te_Active, tab_Locations.Lo_Name" & " FROM tab_Teams LEFT JOIN tab_Locations" & " ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & S & "'"
                                    If Me.AdminType <> "All" Then
                                        sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                    End If
                                    sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        While sqlDataReader.Read = True
                                            If sqlDataReader.Item("Te_Active") = "Yes" Then
                                                TeamSelect = TeamSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & """>" & sqlDataReader.Item("Lo_Name") & " " & sqlDataReader.Item("Te_Name") & vbCrLf
                                            Else
                                                ' INACTIVE... mark that special
                                                'TeamSelect = TeamSelect & "<option value=""" & sqlDataReader.Item("Te_Index") & """> * " & sqlDataReader.Item("Lo_Name") & " " & sqlDataReader.Item("Te_Name") & vbCrLf
                                            End If
                                            namelist = Me.GetTeamMemberNames(sqlDataReader.Item("Te_Index"), False, False)
                                            If namelist <> "" Then
                                                If Len(namelist) > 60 Then
                                                    TeamSelect = TeamSelect & " - " & Left(namelist, 60) & "..."
                                                Else
                                                    TeamSelect = TeamSelect & " - " & namelist
                                                End If
                                            End If
                                            TeamSelect = TeamSelect & "</option>" & vbCrLf

                                        End While
                                        TeamSelect = TeamSelect & "</select>" & vbCrLf
                                        Response_WriteLine("<div class=""container-fluid"">")
                                        Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                                        Response_WriteLine("<p><table border=""1"" bordercolor=""black"" cellspacing=""0"" cellpadding=""0""><tr><td>")
                                        Response_WriteLine("<form name=""form_Reports"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&menu=" & menu & "&S=" & S & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<table>")
                                        Response_WriteLine("<tr><td colspan=""2""><center><input type=""button"" name=""Last1K"" class=""btn btn-primary"" onclick=""location.href='AllSent.aspx'"" value=""All Sent""></center><BR></td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""2"">Reports</th></tr>")
                                        Response_WriteLine("<tr valign=""top""><td>Choose Team</td><td><i>Select Multiple</i> by holding CTRL or SHIFT while selecting<br>")
                                        Response_WriteLine("Note: Inactive teams are not presented for reporting options<br>")
                                        Response_WriteLine("" & TeamSelect & "</td></tr>")
                                        Response_WriteLine("<tr><td>Start Date</td><td><input type=""text"" id=""idStartDate"" name=""form_StartDate"" class=""form-control"" value=""" & Replace(form_StartDate, """", "") & """> mm/dd/yyyy</td></tr>")
                                        Response_WriteLine("<tr><td>End Date</td><td><input type=""text"" id=""idEndDate"" name=""form_EndDate"" class=""form-control"" value=""" & Replace(form_EndDate, """", "") & """> mm/dd/yyyy</td></tr>")
                                        Response_WriteLine("<tr><td colspan=""2""><hr style=""width:100%;color:#58589d;height:1px;background-color:#58589d;""></hr></td></tr>")
                                        Response_WriteLine("<tr><td><b>Completion Rate in Hours</b></td>")
                                        Response_WriteLine("<td><input type=""radio"" id=""Report1"" name=""ReportType"" value=""Completion Rate in Hours"" onclick=""javascript:enableDisableControls();""><font color=""green""> * </font>Show time delays (8a-5p Business Hours) for messages to be closed</td>")
                                        Response_WriteLine("<tr><td><b>Completion Rate in Days</b></td>")
                                        Response_WriteLine("<td><input type=""radio"" id=""Report2"" name=""ReportType"" value=""Completion Rate in DaysC"" onclick=""javascript:enableDisableControls();""><font color=""green""> * </font>Show time delays (non-holiday weekdays - <b>Consolidated Teams</b>) for messages to be closed</td>")
                                        Response_WriteLine("<tr><td><b>Completion Rate in Days</b></td>")
                                        Response_WriteLine("<td><input type=""radio"" id=""Report2A"" name=""ReportType"" value=""Completion Rate in DaysI"" onclick=""javascript:enableDisableControls();""> Show time delays (non-holiday weekdays - <b>Individual Teams</b>) for messages to be closed</td>")
                                        Response_WriteLine("<tr><td><b>Message Totals</b></td>")
                                        Response_WriteLine("<td><input type=""radio"" id=""Report3"" name=""ReportType"" value=""Message Totals"" onclick=""javascript:enableDisableControls();""> Show the totals per day for Messages submitted, closed and open</td>")
                                        Response_WriteLine("<tr><td><b>Reason Totals</b></td>")
                                        Response_WriteLine("<td><input type=""radio"" id=""Report4"" name=""ReportType"" value=""Reason Totals"" onclick=""javascript:enableDisableControls();""> Show the totals per day for each Reason</td></tr>")
                                        Response_WriteLine("<tr><td><b>Average Delays</b></td>")
                                        Response_WriteLine("<td><input type=""radio"" id=""Report5"" name=""ReportType"" value=""Average Delays"" onclick=""javascript:enableDisableControls();""> Show the average (business hour) completion rate per Team & Reason:</td></tr>")
                                        Response_WriteLine("<tr><td><b>Reason</b></td>")
                                        ReasonRadio = "<td><select name=""form_ReportReason"" id=""idReportReason"" class=""form-control"">" & vbCrLf & "<option value="""" selected></option>" & vbCrLf

                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()

                                        MyCommand.CommandText = "SELECT tab_Reasons.Re_Name FROM tab_Reasons WHERE tab_Reasons.Re_Type = 'PACT'" & " AND tab_Reasons.Re_Active = 'Yes' ORDER BY tab_Reasons.Re_SortOrder;"

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            While sqlDataReader.Read = True
                                                ' replace " with encoded quote character 
                                                ' single apostrophe ' = &#39;
                                                ' quote " = &#34;
                                                ' Replace(reasonrs("Re_Name"),"""","&#34;")
                                                ' alternate method would need a DECODE after submit, before can use it:  Server.URLEncode(reasonrs("Re_Name"))
                                                ReasonRadio = ReasonRadio & "<option value=""" & Replace(sqlDataReader.Item("Re_Name"), """", "&#34;") & """>" & sqlDataReader.Item("Re_Name") & "</option>" & vbCrLf
                                            End While

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        ReasonRadio = ReasonRadio & "</select></td></tr><br />"
                                        Response_WriteLine(ReasonRadio)
                                        Response_WriteLine("<br /><tr><td align=""center""><font color=""green""><small>* Suppress Details Output</small></font></td>")
                                        Response_WriteLine("<td><input type=""checkbox"" id=""idSuppressDetails"" name=""form_SuppressDetails"">&nbsp;<font color=""green""><small>(increased performance)</small></font></td></tr>")
                                        Response_WriteLine("<tr><td colspan=""2""><hr style=""width:100%;color:#58589d;height:1px;background-color:#58589d;""></hr></td></tr>")
                                        Response_WriteLine("<tr><td colspan=""2""><center><input type=""submit"" name=""Submit"" class=""btn btn-primary"" value=""Run Report""></center><BR></td></tr>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr></table></p></div></div>")

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End If
                            End If ' form_TeamSelect <> ""

                            ' ************ FUTURE DEV
                            '
                            ' I (Jeff) am working on performance reports and would like to have a reasonably easy way
                            ' to measure response time 
                            '   categorized by   
                            '	  response expectation 
                            '	  and maybe further by message type. 
                            '
                            ' Can I get a count of flagged messages? Maybe subtotaled by sender??
                            ' As a report or as an Admin Menu item to view past flags?
                            ' I could see an Admin menu that showed history of flags 
                            ' - with columns for location, team, assignee, Open/Closed, creator, reason, delay.

                            ' ************ FUTURE DEV
                            '
                            ' NEW REPORT by Individual
                            ' Also, can we get a report to see summary of messages assigned, closed, by individual? The Nurse Manager is asking if we can get that info?
                            ' I think to start something simple, a list of users, selected by location, with columns; #messages assigned, #messages closed, #messages commented?
                            ' I think to start something simple, a list of users, selected by location, with columns; #messages assigned, #messages closed, #messages commented?
                            ' Oh yea date range. Just totals for the date range – I think they are looking at work loads by team.

                            ' ************ FUTURE DEV
                            '
                            ' NEW REPORT by Message Creater
                            ' Suggestion from a site and something I have thought of as well...
                            ' it would be good to obtain "creation of message information" so you can give staff feedback on messages taken, etc.  
                            ' Here is the suggestions...
                            ' I was hoping there was a way I could show the clerks at some of the clinics the increase in 
                            ' VISN 12 messages that are entered by the call center.
                            ' It would kind of be cool to generate a report somehow to obtain information on who is submitting messages, 
                            ' kind of like a "search" by employee to retrieve messages generated by a particular person...just a thought...

                            ' 1-8-2015 meeting with John Provenzano and Esch, Kristie
                            ' Kristie wants a port that will return the COUNTS per reason, per site
                            ' choose a date range
                            '  Select Box of the staff from all those that have sent messages
                            '   counts per reason per site (multiple columns), plus total count (per site and grand total)

                    End Select ' end of the Reports section

                Case Else
                    Response_WriteLine("<p><font color=""red"">ERROR in Admin menu actions.  Should not get here.</font></p>")
            End Select ' Case menu

        End If ' LongI > 0
    End Sub

    Sub ShowScriptsTable(li)
        ' optional - li = LocationIndex to highlight
        Dim sSqlString, cntr, fontcolor


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If li <> 0 And Not IsDBNull(li) Then
            ' li is a string when it comes from a form field
            ' li is an integer when it comes from function lookups
            ' convert it to integer as that's what sqlDataReader.Item("Sc_LocationIndex") refers to.
            li = CInt(li)
        End If
        If Me.AdminSite = "000" Then
            ' show all Sites
            sSqlString = "SELECT tab_Scripts.Sc_Index, tab_Scripts.Sc_ReasonIndex, tab_Scripts.Sc_LocationIndex, tab_Scripts.Sc_Details, tab_Scripts.Sc_Notes" & " FROM tab_Scripts LEFT JOIN tab_Locations ON tab_Scripts.Sc_LocationIndex = tab_Locations.Lo_Index" & " ORDER BY tab_Scripts.Sc_ReasonIndex, tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"

        Else
            ' show only this site
            sSqlString = "SELECT tab_Scripts.Sc_Index, tab_Scripts.Sc_ReasonIndex, tab_Scripts.Sc_LocationIndex, tab_Scripts.Sc_Details, tab_Scripts.Sc_Notes" & " FROM tab_Scripts LEFT JOIN tab_Locations ON tab_Scripts.Sc_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' OR tab_Scripts.Sc_LocationIndex = 0" & " ORDER BY tab_Scripts.Sc_ReasonIndex, tab_Locations.Lo_SortOrder;"
        End If

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""5"">Table_Scripts</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th valign=""bottom"">Index</th>")
                Response_WriteLine("<th>Reason<br>Index</th>")
                Response_WriteLine("<th>Location<br>Index</th>")
                Response_WriteLine("<th valign=""bottom"">Details</th>")
                Response_WriteLine("<th valign=""bottom"">Notes</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If sqlDataReader.Item("Sc_LocationIndex") = li Then
                        fontcolor = "green"
                    Else
                        fontcolor = "black"
                    End If
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    Else
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Sc_Index") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Sc_ReasonIndex") & " <font size=""1"" color=""navy"">" & Me.GetReason(sqlDataReader.Item("Sc_ReasonIndex")) & "</font></td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Sc_LocationIndex") & " <font size=""1"" color=""navy"">" & Me.GetLocationName(sqlDataReader.Item("Sc_LocationIndex")) & "</font></td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Sc_Details") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Sc_Notes") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ShowAdminsTable(au)
        ' optional - au = Admin Username to highlight
        Dim sSqlString, cntr, fontcolor


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If Me.AdminSite = "000" Then
            ' show all Sites
            sSqlString = "SELECT tab_Admins.Adm_Name, tab_Admins.Adm_Username, tab_Admins.Adm_SiteNum, tab_Sites.Si_Name, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type, tab_Admins.Adm_Email, tab_Admins.Adm_FlagOn, tab_Admins.Adm_SID, tab_Admins.Adm_Notes" & " FROM tab_Admins LEFT JOIN tab_Sites ON tab_Admins.Adm_SiteNum = tab_Sites.Si_SiteNum ORDER BY tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type, tab_Admins.Adm_SiteNum, tab_Admins.Adm_Username;"
        Else
            ' show only this Site
            sSqlString = "SELECT tab_Admins.Adm_Name, tab_Admins.Adm_Username, tab_Admins.Adm_SiteNum, tab_Sites.Si_Name, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type, tab_Admins.Adm_Email, tab_Admins.Adm_FlagOn, tab_Admins.Adm_SID, tab_Admins.Adm_Notes" & " FROM tab_Admins LEFT JOIN tab_Sites ON tab_Admins.Adm_SiteNum = tab_Sites.Si_SiteNum" & " WHERE tab_Admins.Adm_SiteNum = '" & Me.AdminSite & "' OR tab_Admins.Adm_SiteNum = '000' ORDER BY tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type, tab_Admins.Adm_SiteNum, tab_Admins.Adm_Username;"
        End If

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""9"">Table_Admins</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th>Name</th>")
                Response_WriteLine("<th>Username</th>")
                Response_WriteLine("<th>SiteNum</th>")
                Response_WriteLine("<th>Access</th>")
                Response_WriteLine("<th>Type</th>")
                Response_WriteLine("<th>Email</th>")
                Response_WriteLine("<th>FlagOn</th>")
                Response_WriteLine("<th>SID</th>")
                Response_WriteLine("<th>Notes</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If UCase(sqlDataReader.Item("Adm_Username")) = UCase(au) Then
                        fontcolor = "green"
                    Else
                        fontcolor = "black"
                    End If
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    Else
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_Name") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_Username") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_SiteNum") & " <font size=""1"" color=""navy"">" & Replace(sqlDataReader.Item("Si_Name"), "Choose Site", "All Sites") & "</font></td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_AccessLevel") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_Type") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_Email") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_FlagOn") & "</td>")
                    If Len(sqlDataReader.Item("Adm_SID")) > 40 Then
                        Response_WriteLine("<td>Valid</td>")
                    Else
                        Response_WriteLine("<td><font color=""red"">Missing</font></td>")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Adm_Notes") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ShowADGroupsTable(aSite)
        ' optional - aSite = Admin Site to highlight (not filter)
        Dim sSqlString, cntr, fontcolor


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If Me.AdminSite = "000" Then
            ' show all Sites
            sSqlString = "SELECT tab_ADGroups.AD_SiteNum, tab_Sites.Si_Name, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_Type, tab_ADGroups.AD_GroupName" & " FROM tab_ADGroups LEFT JOIN tab_Sites ON tab_ADGroups.AD_SiteNum = tab_Sites.Si_SiteNum" & " ORDER BY tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_Type, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName;"
        Else
            ' show only this Site
            sSqlString = "SELECT tab_ADGroups.AD_SiteNum, tab_Sites.Si_Name, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_Type, tab_ADGroups.AD_GroupName" & " FROM tab_ADGroups LEFT JOIN tab_Sites ON tab_ADGroups.AD_SiteNum = tab_Sites.Si_SiteNum" & " WHERE tab_ADGroups.AD_SiteNum= '" & Me.AdminSite & "' OR tab_ADGroups.AD_SiteNum = '000'" & " ORDER BY tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_Type, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName;"
        End If

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""4"">Table_ADGroups</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th>SiteNum</th>")
                Response_WriteLine("<th>Type</th>")
                Response_WriteLine("<th>Access</th>")
                Response_WriteLine("<th>GroupName</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If sqlDataReader.Item("AD_SiteNum") = aSite Then
                        fontcolor = "green"
                    Else
                        fontcolor = "black"
                    End If
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    Else
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("AD_SiteNum") & " <font size=""1"" color=""navy"">" & Replace(sqlDataReader.Item("Si_Name"), "Choose Site", "All Sites") & "</font></td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("AD_Type") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("AD_AccessLevel") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("AD_GroupName") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ShowSitesTable(sn)
        ' optional - sn = Site Name to highlight
        Dim sSqlString, cntr, fontcolor


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If Me.AdminSite = "000" Then
            ' show all Sites
            sSqlString = "SELECT * FROM tab_Sites ORDER BY tab_Sites.Si_SiteOrder;"
        Else
            ' show only this Site
            sSqlString = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Sites.Si_SiteOrder;"
        End If

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""4"">Table_Sites</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th>SiteOrder</th>")
                Response_WriteLine("<th>SiteNum</th>")
                Response_WriteLine("<th>SiteName</th>")
                Response_WriteLine("<th>Active</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If UCase(sqlDataReader.Item("Si_SiteNum")) = UCase(sn) And sn <> "000" Then
                        fontcolor = "green"
                    Else
                        fontcolor = "black"
                    End If
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    Else
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Si_SiteOrder") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Si_SiteNum") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Si_Name") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Si_Active") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ShowLocationsTable(sn)
        ' optional - sn = SiteNum to highlight
        Dim sSqlString, cntr, fontcolor


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If Me.AdminSite = "000" Then
            ' show all Sites
            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder, tab_Locations.Lo_SiteNum, tab_Sites.Si_Name, tab_Locations.Lo_Name, tab_Locations.Lo_Type, tab_Locations.Lo_Active" & " FROM tab_Locations LEFT JOIN tab_Sites ON tab_Locations.Lo_SiteNum = tab_Sites.Si_SiteNum" & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
        Else
            ' show only this Site
            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder, tab_Locations.Lo_SiteNum, tab_Sites.Si_Name, tab_Locations.Lo_Name, tab_Locations.Lo_Type, tab_Locations.Lo_Active" & " FROM tab_Locations LEFT JOIN tab_Sites ON tab_Locations.Lo_SiteNum = tab_Sites.Si_SiteNum" & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
        End If

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""6"">Table_Locations</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th>Index</th>")
                Response_WriteLine("<th>SortOrder</th>")
                Response_WriteLine("<th>SiteNum</th>")
                Response_WriteLine("<th>Name</th>")
                Response_WriteLine("<th>ReasonType</th>")
                Response_WriteLine("<th>Active</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If UCase(sqlDataReader.Item("Lo_SiteNum")) = UCase(sn) Then
                        fontcolor = "green"
                    Else
                        fontcolor = "black"
                    End If
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    Else
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Index") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Lo_SortOrder") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Lo_SiteNum") & " <font size=""1"" color=""navy"">" & sqlDataReader.Item("Si_Name") & "</font></td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Name") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Type") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Lo_Active") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ShowTeamsTable(ssi)
        ' optional - ssi = LocationIndex to highlight
        Dim sSqlString, cntr, fontcolor


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        If ssi.ToString <> "" And Not IsDBNull(ssi) Then
            ' ssi is a string when it comes from a form field
            ' ssi is an integer when it comes from function lookups
            ' convert it to integer as that's what sqlDataReader.Item("Te_LocationIndex") refers to.
            ssi = CInt(ssi)
        Else
            ssi = 0
        End If
        If Me.AdminSite = "000" Then
            ' show all Sites
            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder, tab_Teams.Te_LocationIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name, tab_Teams.Te_Active, tab_Teams.Te_Notes" & " FROM tab_Teams LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
        Else
            ' show only this site
            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder, tab_Teams.Te_LocationIndex, tab_Locations.Lo_Name, tab_Teams.Te_Name, tab_Teams.Te_Active, tab_Teams.Te_Notes" & " FROM tab_Teams LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
        End If

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""6"">Table_Teams</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th>Index</th>")
                Response_WriteLine("<th>SortOrder</th>")
                Response_WriteLine("<th>LocationIndex</th>")
                Response_WriteLine("<th>Name</th>")
                Response_WriteLine("<th>Active</th>")
                Response_WriteLine("<th>Notes</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If sqlDataReader.Item("Te_LocationIndex") = ssi Then
                        fontcolor = "green"
                    Else
                        fontcolor = "black"
                    End If
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    Else
                        Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Te_Index") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Te_SortOrder") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Te_LocationIndex") & " <font size=""1"" color=""navy"">" & sqlDataReader.Item("Lo_Name") & "</font></td>")
                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                        Response_WriteLine("<td>" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</td>")
                    Else
                        Response_WriteLine("<td>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</td>")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Te_Active") & "</td>")
                    Response_WriteLine("<td>" & sqlDataReader.Item("Te_Notes") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ShowMembersTable(ti, pu)

        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        ' ti = optional - TeamIndex of member to highlight
        ' pu = optional - username of member to highlight

        If IsNumeric(ti) Then
            ' ti is a string when it comes from a form field
            ' ti is an integer when it comes from function lookups
            ' convert it to integer as that's what sqlDataReader.Item("Me_TeamIndex") refers to.
            ti = CInt(ti)
        End If

        Dim Showtype
        If (Not Request.QueryString("Showtype") Is Nothing) Then Showtype = Request.QueryString("Showtype").ToString() Else Showtype = ""
        If Me.AdminSite <> "000" And Showtype <> Me.AdminSite Then
            ' override Showtype in case non-000 Admin used a QueryString adjustment
            Showtype = Me.AdminSite
        End If

        Dim sSqlString, cntr, fontcolor
        If ti <> 0 And Not IsDBNull(ti) Then
            ' now find the default Site to show for this ti
            Showtype = Me.GetSiteNum(Me.GetLocationIndex(ti))
        End If

        If pu <> "" And Not IsDBNull(pu) Then
            ' get SiteNum from username
            sSqlString = "SELECT TOP 1 tab_Sites.Si_SiteNum" & " FROM ((tab_Sites LEFT JOIN tab_Locations ON tab_Sites.Si_SiteNum = tab_Locations.Lo_SiteNum)" & " LEFT JOIN tab_Teams ON tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex)" & " LEFT JOIN tab_Members ON tab_Teams.Te_Index = tab_Members.Me_TeamIndex" & " WHERE tab_Members.Me_Username LIKE '" & pu & "';"

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If sqlDataReader.Read = True Then
                    Showtype = sqlDataReader.Item("Si_SiteNum")
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If

        ' correct for failure to load	
        If Showtype = "" Or IsDBNull(Showtype) Then
            Showtype = Me.AdminSite
        End If

        'Response.Write("AdminSite=" & AdminSite & "<br>")
        'Response.Write("ti=" & ti & "<br>")
        'Response.Write("pu=" & pu & "<br>")

        ' ViewMembers entry, or ViewMembers repeat entry, or admin catch-all
        If (Me.AdminSite = "000" And Showtype = "") Or (Me.AdminSite = "000" And ti = 0 And pu = "") Or Showtype = "000" Then
            ' show choice to pick Site
            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name FROM tab_Sites WHERE Si_SiteNum <> '000' ORDER BY tab_Sites.Si_SiteOrder;"

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If sqlDataReader.HasRows = True Then
                    Response_WriteLine("<p>")
                    cntr = 0
                    While sqlDataReader.Read = True
                        If cntr > 0 Then
                            Response_WriteLine("- ")
                        End If
                        Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=ViewMember&Showtype=" & sqlDataReader.Item("Si_SiteNum") & """>")
                        If Showtype = sqlDataReader.Item("Si_SiteNum") Then
                            Response_WriteLine("<b>" & sqlDataReader.Item("Si_SiteNum") & "</b>")
                        Else
                            Response_WriteLine("" & sqlDataReader.Item("Si_SiteNum") & "")
                        End If
                        Response_WriteLine("</a>")
                        cntr = cntr + 1
                    End While
                    Response_WriteLine("</p>")
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If

        If Showtype = "" Or Showtype = "000" Then
            ' not chosen yet
            Response_WriteLine("<p>Choose Site</p>")
        Else

            ' show this srs SiteNum only
            sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder, tab_Members.Me_TeamIndex, tab_Members.Me_Name, tab_Members.Me_Title, tab_Members.Me_Username," & " tab_Members.Me_Email, tab_Members.Me_EmailNew, tab_Members.Me_EmailAssign, tab_Members.Me_EmailStatus," & " tab_Members.Me_ShowOn, tab_Members.Me_Active, tab_Members.Me_SID, tab_Members.Me_Notes, tab_Teams.Te_Name" & " FROM (tab_Members LEFT JOIN tab_Teams ON tab_Members.Me_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Locations.Lo_SiteNum = '" & Showtype & "'" & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Members.Me_SortOrder;"

            'Response.Write("sSqlString=" & sSqlString & "<br>")

            MyCommand.CommandText = sSqlString

            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    Response_WriteLine("<p>Members Table Not Found</p>")
                Else
                    cntr = 0
                    Response_WriteLine("<p><div class=""container-fluid"">")
                    Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                    Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                    Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                    Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""14"">Table_Members for Site " & Showtype & "</th></tr>")
                    Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                    Response_WriteLine("<th>Index</th>")
                    Response_WriteLine("<th>SortOrder</th>")
                    Response_WriteLine("<th>TeamIndex</th>")
                    Response_WriteLine("<th>Name</th>")
                    Response_WriteLine("<th>Title</th>")
                    Response_WriteLine("<th>Username</th>")
                    Response_WriteLine("<th>Email</th>")
                    Response_WriteLine("<th nowrap>E-New</th>")
                    Response_WriteLine("<th nowrap>E-Assign</th>")
                    Response_WriteLine("<th nowrap>E-Status</th>")
                    Response_WriteLine("<th>ShowOn</th>")
                    Response_WriteLine("<th>Active</th>")
                    Response_WriteLine("<th>SID</th>")
                    Response_WriteLine("<th>Notes</th>")
                    Response_WriteLine("</tr>")
                    While sqlDataReader.Read = True
                        If UCase(sqlDataReader.Item("Me_Username")) = UCase(pu) Then
                            fontcolor = "red"
                        Else
                            If sqlDataReader.Item("Me_TeamIndex") = ti Then
                                fontcolor = "green"
                            Else
                                fontcolor = "black"
                            End If
                        End If
                        If cntr Mod 2 = 0 Then
                            Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                        Else
                            Response_WriteLine("<tr style=""color:" & fontcolor & ";vertical-align:top"">")
                        End If
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Index") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_SortOrder") & "</td>")
                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                            Response_WriteLine("<td>" & sqlDataReader.Item("Me_TeamIndex") & " <font size=""1"" color=""navy"">" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</font></td>")
                        Else
                            Response_WriteLine("<td>" & sqlDataReader.Item("Me_TeamIndex") & " <font size=""1"" color=""navy"">" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</font></td>")
                        End If
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Name") & "</td>")
                        If IsDBNull(sqlDataReader.Item("Me_Title")) Then
                            Response_WriteLine("<td>&nbsp;</td>")
                        Else
                            Response_WriteLine("<td>" & sqlDataReader.Item("Me_Title") & "</td>")
                        End If
                        Response_WriteLine("<td nowrap>" & sqlDataReader.Item("Me_Username") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Email") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_EmailNew") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_EmailAssign") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_EmailStatus") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_ShowOn") & "</td>")
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Active") & "</td>")
                        If Len(sqlDataReader.Item("Me_SID")) > 40 Then
                            Response_WriteLine("<td>Valid</td>")
                        Else
                            Response_WriteLine("<td><font color=""red"">Missing</font></td>")
                        End If
                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Notes") & "</td>")
                        Response_WriteLine("</tr>")
                        cntr = cntr + 1
                    End While
                    Response_WriteLine("</table>")
                    Response_WriteLine("</td></tr></table>")
                    Response_WriteLine("</div></div></p>")
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try

        End If
    End Sub

    Sub ShowHolidaysTable()
        Dim sSqlString, cntr


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        sSqlString = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays ORDER BY Ho_Date DESC;"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.HasRows = True Then
                cntr = 0
                Response_WriteLine("<p>")
                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""4"">Table_Holidays</th></tr>")
                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                Response_WriteLine("<th>Date</th>")
                Response_WriteLine("<th>Hame</th>")
                Response_WriteLine("</tr>")
                While sqlDataReader.Read = True
                    If cntr Mod 2 = 0 Then
                        Response_WriteLine("<tr>")
                    Else
                        Response_WriteLine("<tr>")
                    End If
                    If DatePart("yyyy", theDate) = DatePart("yyyy", sqlDataReader.Item("Ho_Date")) Then
                        Response_WriteLine("<td><font color=""navy"">" & sqlDataReader.Item("Ho_Date") & "</font></td>")
                    Else
                        Response_WriteLine("<td>" & sqlDataReader.Item("Ho_Date") & "</td>")
                    End If
                    Response_WriteLine("<td>" & sqlDataReader.Item("Ho_Name") & "</td>")
                    Response_WriteLine("</tr>")
                    cntr = cntr + 1
                End While
                Response_WriteLine("</table>")
                Response_WriteLine("</td></tr></table>")
                Response_WriteLine("</p>")
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ReSortSite(sn, so)
        ' sn = SiteNum (String)
        ' so = new SortOrder (String)
        '	= "AAAnn" = desired new value
        '	= "ZZZ" = move to end

        Dim sSqlString
        Dim oldSortOrder, maxSortOrder

        sSqlString = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & sn & "';"


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing
        Dim sqlDataReader2 As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyConnection2 = New SqlConnection(strConn)

        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim MyCommand2 As New SqlCommand()
        MyCommand2.Connection = MyConnection2
        MyCommand2.CommandType = CommandType.Text

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder - SiteNum not found.</font></p>")
            Else
                ' store for easy use.
                oldSortOrder = sqlDataReader.Item("Si_SiteOrder")

                ' first compute correct sortorder
                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                ' when ZZZ, remove ZZZ and
                '   shift (sites > old sortorder) down by 10
                '   update as is.
                ' when AAA, remove AAA and
                '   if new SortOrder = old SortOrder, do nothing
                '   if new SortOrder < old SortOrder
                '      shift (sites < old SortOrder) and (sites >= new SortOrder) up by 10
                '	     update SortOrder
                '   if new SortOrder > old SortOrder
                '      shift (sites > old SortOrder) and (sites < new SortOrder) down by 10.
                '      update SortOrder
                If InStr(so, "ZZZ") Then
                    '   shift (sites > old SortOrder) down by 10
                    maxSortOrder = 10
                    sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_SiteOrder FROM tab_Sites WHERE tab_Sites.Si_SiteOrder > " & oldSortOrder & " ORDER BY tab_Sites.Si_SiteOrder;"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString=" & sSqlString & "<br>")
                    End If

                    MyCommand2.CommandText = sSqlString

                    Try
                        If MyConnection2.State = ConnectionState.Closed Then
                            MyConnection2.Open()
                        End If

                        sqlDataReader2 = MyCommand2.ExecuteReader

                        If Not sqlDataReader2.HasRows Then
                            ' none exist higher than old order
                        Else
                            While sqlDataReader2.Read = True
                                If sqlDataReader2.Item("Si_SiteOrder") > maxSortOrder Then
                                    maxSortOrder = sqlDataReader2.Item("Si_SiteOrder")
                                End If
                                UpdateTableRecord("UPDATE tab_Sites SET tab_Sites.Si_SiteOrder = " & sqlDataReader2.Item("Si_SiteOrder") - 10 & " WHERE tab_Sites.Si_SiteNum = '" & sqlDataReader2.Item("Si_SiteNum") & "';")
                                Response.Write("Site " & sqlDataReader2.Item("Si_SiteNum") & " SortOrder updated from " & sqlDataReader2.Item("Si_SiteOrder") & " to " & sqlDataReader2.Item("Si_SiteOrder") - 10 & ".<br>")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ' new End of SortOrder value
                    so = CInt(maxSortOrder)
                    If so < oldSortOrder Then
                        ' already is at end of sort order so don't move
                        so = oldSortOrder
                    End If
                End If

                If InStr(so, "AAA") Then
                    so = Replace(so, "AAA", "")
                    so = CInt(so)
                    '   if new SortOrder < old SortOrder
                    If so < oldSortOrder Then
                        '	  shift (sites < old SortOrder) and (sites >= new SortOrder) up by 10
                        sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_SiteOrder FROM tab_Sites" & " WHERE tab_Sites.Si_SiteOrder < " & oldSortOrder & " AND tab_Sites.Si_SiteOrder >= " & so & " ORDER BY tab_Sites.Si_SiteOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' strange, should not get here as the form already guaranteed they would exist
                                Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Sites SET tab_Sites.Si_SiteOrder = " & sqlDataReader2.Item("Si_SiteOrder") + 10 & " WHERE tab_Sites.Si_SiteNum = '" & sqlDataReader2.Item("Si_SiteNum") & "';")
                                    Response.Write("Site " & sqlDataReader2.Item("Si_SiteNum") & " SortOrder updated from " & sqlDataReader2.Item("Si_SiteOrder") & " to " & sqlDataReader2.Item("Si_SiteOrder") + 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If
                    '   if new SortOrder > old SortOrder
                    If so > oldSortOrder Then
                        '	  shift (sites > old SortOrder) and (sites < new SortOrder) down by 10.
                        sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_SiteOrder FROM tab_Sites" & " WHERE tab_Sites.Si_SiteOrder > " & oldSortOrder & " AND tab_Sites.Si_SiteOrder < " & so & " ORDER BY tab_Sites.Si_SiteOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' get here when trying to insert before the next location in line... so really... it's the same.
                                Response_WriteLine("<p><font color=""green"">Not adjusting SortOrder - attempted to insert before the next Site is where it is already.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Sites SET tab_Sites.Si_SiteOrder = " & sqlDataReader2.Item("Si_SiteOrder") - 10 & " WHERE tab_Sites.Si_SiteNum = '" & sqlDataReader2.Item("Si_SiteNum") & "';")
                                    Response.Write("Site " & sqlDataReader2.Item("Si_SiteNum") & " SortOrder updated from " & sqlDataReader2.Item("Si_SiteOrder") & " to " & sqlDataReader2.Item("Si_SiteOrder") - 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        ' inserting "before" the one selected so really is 10 less.
                        so = so - 10
                    End If
                End If

                ' second store new sort order
                If oldSortOrder <> so Then
                    UpdateTableRecord("UPDATE tab_Sites SET tab_Sites.Si_SiteOrder = '" & so & "' WHERE tab_Sites.Si_SiteNum = '" & sn & "';")
                    'On Error Resume Next
                    If Err.Number = 0 Then
                        Response_WriteLine("<p><font color=""green"">SortOrder updated successfully from " & oldSortOrder & " to " & so & ".</font></p>")
                    Else
                        Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder.</font></p>")
                    End If
                Else
                    ' skip, not changed
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ReSortLocation(si, so)
        ' si = LocationIndex (Int)
        ' so = new SortOrder (String)
        '	= "AAAnn" = desired new value
        '	= "ZZZ" = move to end

        Dim sSqlString
        Dim oldSortOrder, maxSortOrder


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing
        Dim sqlDataReader2 As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyConnection2 = New SqlConnection(strConn)

        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim MyCommand2 As New SqlCommand()
        MyCommand2.Connection = MyConnection2
        MyCommand2.CommandType = CommandType.Text

        sSqlString = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_Index = " & si & ";"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder - LocationIndex not found.</font></p>")
            Else
                ' store for easy use.
                oldSortOrder = sqlDataReader.Item("Lo_SortOrder")

                ' first compute correct sortorder
                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                ' when ZZZ, remove ZZZ and
                '   shift (locations > old sortorder) down by 10
                '   update as is.
                ' when AAA, remove AAA and
                '   if new SortOrder = old SortOrder, do nothing
                '   if new SortOrder < old SortOrder
                '	  shift (Locations < old SortOrder) and (Locations >= new SortOrder) up by 10
                '	  update SortOrder
                '   if new SortOrder > old SortOrder
                '	  shift (Locations > old SortOrder) and (Locations < new SortOrder) down by 10.
                '	  update SortOrder
                If InStr(so, "ZZZ") Then
                    '   shift (Locations > old SortOrder) down by 10
                    maxSortOrder = 10
                    sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder FROM tab_Locations" & " WHERE tab_Locations.Lo_SiteNum = '" & sqlDataReader.Item("Lo_SiteNum") & "'" & " AND tab_Locations.Lo_SortOrder > " & oldSortOrder & " ORDER BY tab_Locations.Lo_SortOrder;"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString=" & sSqlString & "<br>")
                    End If

                    MyCommand2.CommandText = sSqlString

                    Try
                        If MyConnection2.State = ConnectionState.Closed Then
                            MyConnection2.Open()
                        End If

                        sqlDataReader2 = MyCommand2.ExecuteReader

                        If Not sqlDataReader2.HasRows Then
                            ' none exist higher than old order
                        Else
                            While sqlDataReader2.Read = True
                                If sqlDataReader2.Item("Lo_SortOrder") > maxSortOrder Then
                                    maxSortOrder = sqlDataReader2.Item("Lo_SortOrder")
                                End If
                                UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_SortOrder = " & sqlDataReader2.Item("Lo_SortOrder") - 10 & " WHERE tab_Locations.Lo_Index = " & sqlDataReader2.Item("Lo_Index") & ";")
                                Response.Write("Location " & sqlDataReader2.Item("Lo_Index") & " SortOrder updated from " & sqlDataReader2.Item("Lo_SortOrder") & " to " & sqlDataReader2.Item("Lo_SortOrder") - 10 & ".<br>")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ' new End of SortOrder value
                    so = CInt(maxSortOrder)
                    If so < oldSortOrder Then
                        ' already is at end of sort order so don't move
                        so = oldSortOrder
                    End If
                End If

                If InStr(so, "AAA") Then
                    so = Replace(so, "AAA", "")
                    so = CInt(so)
                    '   if new SortOrder < old SortOrder
                    If so < oldSortOrder Then
                        '	  shift (Locations < old SortOrder) and (Locations >= new SortOrder) up by 10
                        sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder FROM tab_Locations" & " WHERE tab_Locations.Lo_SiteNum = '" & sqlDataReader.Item("Lo_SiteNum") & "'" & " AND tab_Locations.Lo_SortOrder < " & oldSortOrder & " AND tab_Locations.Lo_SortOrder >= " & so & " ORDER BY tab_Locations.Lo_SortOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' strange, should not get here as the form already guaranteed they would exist
                                Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_SortOrder = " & sqlDataReader2.Item("Lo_SortOrder") + 10 & " WHERE tab_Locations.Lo_Index = " & sqlDataReader2.Item("Lo_Index") & ";")
                                    Response.Write("Location " & sqlDataReader2.Item("Lo_Index") & " SortOrder updated from " & sqlDataReader2.Item("Lo_SortOrder") & " to " & sqlDataReader2.Item("Lo_SortOrder") + 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If
                    '   if new SortOrder > old SortOrder
                    If so > oldSortOrder Then
                        '	  shift (Locations > old SortOrder) and (Locations < new SortOrder) down by 10.
                        sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder FROM tab_Locations" & " WHERE tab_Locations.Lo_SiteNum = '" & sqlDataReader.Item("Lo_SiteNum") & "'" & " AND tab_Locations.Lo_SortOrder > " & oldSortOrder & " AND tab_Locations.Lo_SortOrder < " & so & " ORDER BY tab_Locations.Lo_SortOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' get here when trying to insert before the next location in line... so really... it's the same.
                                Response_WriteLine("<p><font color=""green"">Not adjusting SortOrder - attempted to insert before the next Location is where it is already.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_SortOrder = " & sqlDataReader2.Item("Lo_SortOrder") - 10 & " WHERE tab_Locations.Lo_Index = " & sqlDataReader2.Item("Lo_Index") & ";")
                                    Response.Write("Location " & sqlDataReader2.Item("Lo_Index") & " SortOrder updated from " & sqlDataReader2.Item("Lo_SortOrder") & " to " & sqlDataReader2.Item("Lo_SortOrder") - 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        ' inserting "before" the one selected so really is 10 less.
                        so = so - 10
                    End If
                End If

                ' second store new sort order
                If oldSortOrder <> so Then
                    UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_SortOrder = '" & so & "' WHERE tab_Locations.Lo_Index = " & si & ";")
                    'On Error Resume Next
                    If Err.Number = 0 Then
                        Response_WriteLine("<p><font color=""green"">SortOrder updated successfully from " & oldSortOrder & " to " & so & ".</font></p>")
                    Else
                        Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder.</font></p>")
                    End If
                Else
                    ' skip, not changed
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ReSortTeam(ti, so)
        ' ti = TeamIndex (Int)
        ' so = new SortOrder (String)
        '	= "AAAnn" = desired new value
        '	= "ZZZ" = move to end

        Dim sSqlString
        Dim oldSortOrder, maxSortOrder


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing
        Dim sqlDataReader2 As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyConnection2 = New SqlConnection(strConn)

        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim MyCommand2 As New SqlCommand()
        MyCommand2.Connection = MyConnection2
        MyCommand2.CommandType = CommandType.Text

        sSqlString = "SELECT * FROM tab_Teams WHERE tab_Teams.Te_Index = " & ti & ";"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder - TeamIndex not found.</font></p>")
            Else
                ' store for easy use.
                oldSortOrder = sqlDataReader.Item("Te_SortOrder")

                ' first compute correct sortorder
                ' comes in as: "AAA10, AAA20, AAA30... ZZZ"
                ' when ZZZ, remove ZZZ and
                '   shift (Teams > old sortorder) down by 10
                '   updaate SortOrder with previous max SortOrder
                ' when AAA, remove AAA and
                '   if new SortOrder = old SortOrder, do nothing
                '   if new SortOrder < old SortOrder
                '      shift (Teams < old SortOrder) and (Teams >= new SortOrder) up by 10
                '      update SortOrder
                '   if new SortOrder > old SortOrder
                '      shift (Teams > old SortOrder) and (Teams < new SortOrder) down by 10.
                '      update SortOrder
                If InStr(so, "ZZZ") Then
                    '   shift (Teams > old SortOrder) down by 10
                    maxSortOrder = 10
                    sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder FROM tab_Teams" & " WHERE tab_Teams.Te_LocationIndex = " & sqlDataReader.Item("Te_LocationIndex") & " AND tab_Teams.Te_SortOrder > " & oldSortOrder & " ORDER BY tab_Teams.Te_SortOrder;"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString=" & sSqlString & "<br>")
                    End If

                    MyCommand2.CommandText = sSqlString

                    Try
                        If MyConnection2.State = ConnectionState.Closed Then
                            MyConnection2.Open()
                        End If

                        sqlDataReader2 = MyCommand2.ExecuteReader

                        If Not sqlDataReader2.HasRows Then
                            ' none exist higher than old order
                        Else
                            While sqlDataReader2.Read = True
                                If sqlDataReader2.Item("Te_SortOrder") > maxSortOrder Then
                                    maxSortOrder = sqlDataReader2.Item("Te_SortOrder")
                                End If
                                UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_SortOrder = " & sqlDataReader2.Item("Te_SortOrder") - 10 & " WHERE tab_Teams.Te_Index = " & sqlDataReader2.Item("Te_Index") & ";")
                                Response.Write("Team " & sqlDataReader2.Item("Te_Index") & " SortOrder updated from " & sqlDataReader2.Item("Te_SortOrder") & " to " & sqlDataReader2.Item("Te_SortOrder") - 10 & ".<br>")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ' new End of SortOrder value
                    so = CInt(maxSortOrder)
                    If so < oldSortOrder Then
                        ' already is at end of sort order so don't move
                        so = oldSortOrder
                    End If
                End If

                If InStr(so, "AAA") Then
                    so = Replace(so, "AAA", "")
                    so = CInt(so)
                    '   if new SortOrder < old SortOrder
                    If so < oldSortOrder Then
                        '	  shift (Teams < old SortOrder) and (Teams >= new SortOrder) up by 10
                        sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder FROM tab_Teams" & " WHERE tab_Teams.Te_LocationIndex = " & sqlDataReader.Item("Te_LocationIndex") & " AND tab_Teams.Te_SortOrder < " & oldSortOrder & " AND tab_Teams.Te_SortOrder >= " & so & " ORDER BY tab_Teams.Te_SortOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' strange, should not get here as the form already guaranteed they would exist
                                Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_SortOrder = " & sqlDataReader2.Item("Te_SortOrder") + 10 & " WHERE tab_Teams.Te_Index = " & sqlDataReader2.Item("Te_Index") & ";")
                                    Response.Write("Team " & sqlDataReader2.Item("Te_Index") & " SortOrder updated from " & sqlDataReader2.Item("Te_SortOrder") & " to " & sqlDataReader2.Item("Te_SortOrder") + 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If
                    '   if new SortOrder > old SortOrder
                    If so > oldSortOrder Then
                        '	  shift (tab_Teams > old SortOrder) and (tab_Teams < new SortOrder) down by 10.
                        sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder FROM tab_Teams" & " WHERE tab_Teams.Te_LocationIndex = " & sqlDataReader.Item("Te_LocationIndex") & " AND tab_Teams.Te_SortOrder > " & oldSortOrder & " AND tab_Teams.Te_SortOrder < " & so & " ORDER BY tab_Teams.Te_SortOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' get here when trying to insert before the next Team in line... so really... it's the same.
                                Response_WriteLine("<p><font color=""green"">Not adjusting SortOrder - attempted to insert before the next Team is where it is already.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_SortOrder = " & sqlDataReader2.Item("Te_SortOrder") - 10 & " WHERE tab_Teams.Te_Index = " & sqlDataReader2.Item("Te_Index") & ";")
                                    Response.Write("Team " & sqlDataReader2.Item("Te_Index") & " SortOrder updated from " & sqlDataReader2.Item("Te_SortOrder") & " to " & sqlDataReader2.Item("Te_SortOrder") - 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        ' inserting "before" the one selected so really is 10 less.
                        so = so - 10
                    End If
                End If

                ' second store new sort order
                If oldSortOrder <> so Then
                    UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_SortOrder = '" & so & "' WHERE tab_Teams.Te_Index = " & ti & ";")
                    'On Error Resume Next
                    If Err.Number = 0 Then
                        Response_WriteLine("<p><font color=""green"">SortOrder updated successfully from " & oldSortOrder & " to " & so & ".</font></p>")
                    Else
                        Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder.</font></p>")
                    End If
                Else
                    ' skip, not changed
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub

    Sub ReSortMember(pi, so)
        ' pi = MemberIndex (Int)
        ' so = new SortOrder (String)
        '	= "AAAnn" = desired new value
        '	= "ZZZ" = move to end

        Dim sSqlString
        Dim oldSortOrder, maxSortOrder


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing
        Dim sqlDataReader2 As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyConnection2 = New SqlConnection(strConn)

        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim MyCommand2 As New SqlCommand()
        MyCommand2.Connection = MyConnection2
        MyCommand2.CommandType = CommandType.Text

        sSqlString = "SELECT * FROM tab_Members WHERE tab_Members.Me_Index = " & pi & ";"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder - MemberIndex not found.</font></p>")
            Else
                ' store for easy use.
                oldSortOrder = sqlDataReader.Item("Me_SortOrder")

                ' first compute correct sortorder
                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                ' when ZZZ, remove ZZZ and
                '   shift (members > old sortorder) down by 10
                '   update as is.
                ' when AAA, remove AAA and
                '   if new SortOrder = old SortOrder, do nothing
                '   if new SortOrder < old SortOrder
                '      shift (members < old SortOrder) and (members >= new SortOrder) up by 10
                '      update SortOrder
                '   if new SortOrder > old SortOrder
                '      shift (members > old SortOrder) and (members < new SortOrder) down by 10.
                '      update SortOrder
                If InStr(so, "ZZZ") Then
                    '   shift (members > old SortOrder) down by 10
                    maxSortOrder = 10
                    sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Me_TeamIndex") & " AND tab_Members.Me_SortOrder > " & oldSortOrder & " ORDER BY tab_Members.Me_SortOrder;"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString=" & sSqlString & "<br>")
                    End If

                    MyCommand2.CommandText = sSqlString

                    Try
                        If MyConnection2.State = ConnectionState.Closed Then
                            MyConnection2.Open()
                        End If

                        sqlDataReader2 = MyCommand2.ExecuteReader

                        If Not sqlDataReader2.HasRows Then
                            ' none exist higher than old order
                        Else
                            While sqlDataReader2.Read = True
                                If sqlDataReader2.Item("Me_SortOrder") > maxSortOrder Then
                                    maxSortOrder = sqlDataReader2.Item("Me_SortOrder")
                                End If
                                UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SortOrder = " & sqlDataReader2.Item("Me_SortOrder") - 10 & " WHERE tab_Members.Me_Index = " & sqlDataReader2.Item("Me_Index") & ";")
                                Response.Write("Member " & sqlDataReader2.Item("Me_Index") & " SortOrder updated from " & sqlDataReader2.Item("Me_SortOrder") & " to " & sqlDataReader2.Item("Me_SortOrder") - 10 & ".<br>")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    ' new End of SortOrder value
                    so = CInt(maxSortOrder)
                    If so < oldSortOrder Then
                        ' already is at end of sort order so don't move
                        so = oldSortOrder
                    End If
                End If

                If InStr(so, "AAA") Then
                    so = Replace(so, "AAA", "")
                    so = CInt(so)
                    '   if new SortOrder < old SortOrder
                    If so < oldSortOrder Then
                        '	  shift (members < old SortOrder) and (members >= new SortOrder) up by 10
                        sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Me_TeamIndex") & " AND tab_Members.Me_SortOrder < " & oldSortOrder & " AND tab_Members.Me_SortOrder >= " & so & " ORDER BY tab_Members.Me_SortOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' strange, should not get here as the form already guaranteed they would exist
                                Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SortOrder = " & sqlDataReader2.Item("Me_SortOrder") + 10 & " WHERE tab_Members.Me_Index = " & sqlDataReader2.Item("Me_Index") & ";")
                                    Response.Write("Member " & sqlDataReader2.Item("Me_Index") & " SortOrder updated from " & sqlDataReader2.Item("Me_SortOrder") & " to " & sqlDataReader2.Item("Me_SortOrder") + 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If
                    '   if new SortOrder > old SortOrder
                    If so > oldSortOrder Then
                        '	  shift (members > old SortOrder) and (members < new SortOrder) down by 10.
                        sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Me_TeamIndex") & " AND tab_Members.Me_SortOrder > " & oldSortOrder & " AND tab_Members.Me_SortOrder < " & so & " ORDER BY tab_Members.Me_SortOrder;"
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        MyCommand2.CommandText = sSqlString

                        Try
                            If MyConnection2.State = ConnectionState.Closed Then
                                MyConnection2.Open()
                            End If

                            sqlDataReader2 = MyCommand2.ExecuteReader

                            If Not sqlDataReader2.HasRows Then
                                ' get here when trying to insert before the next person in line... so really... it's the same.
                                Response_WriteLine("<p><font color=""green"">Not adjusting SortOrder - attempted to insert before the next Member is where it is already.</font></p>")
                            Else
                                While sqlDataReader2.Read = True
                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SortOrder = " & sqlDataReader2.Item("Me_SortOrder") - 10 & " WHERE tab_Members.Me_Index = " & sqlDataReader2.Item("Me_Index") & ";")
                                    Response.Write("Member " & sqlDataReader2.Item("Me_Index") & " SortOrder updated from " & sqlDataReader2.Item("Me_SortOrder") & " to " & sqlDataReader2.Item("Me_SortOrder") - 10 & ".<br>")
                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        ' inserting "before" the one selected so really is 10 less.
                        so = so - 10
                    End If
                End If

                ' second store new sort order
                If oldSortOrder <> so Then
                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SortOrder = '" & so & "' WHERE tab_Members.Me_Index = " & pi & ";")
                    'On Error Resume Next
                    If Err.Number = 0 Then
                        Response_WriteLine("<p><font color=""green"">SortOrder updated successfully from " & oldSortOrder & " to " & so & ".</font></p>")
                    Else
                        Response_WriteLine("<p><font color=""red"">ERROR updating SortOrder.</font></p>")
                    End If
                Else
                    ' skip, not changed
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

    End Sub
    Function ReconcileReasonInlineStyle(sReason) As String
        Dim Result As String = ""
        If sReason = "VISN Clinical Contact Center Triage – within 24 hours" Or sReason = "VISN Pharmacy CCC – Window" Or sReason = "Medication (local mail)" Then
            Result = "style=background-color:green;font-weight:bold;color:#ffffff;"
        ElseIf sReason = "VISN Clinical Contact Center Triage – within 4 hours" Or sReason = "Medication (expedited mail)" Or sReason = "Call Transfer" Or sReason = "GENERAL" Then
            Result = "style=background-color:yellow;font-weight:bold;color:#000000;"
        ElseIf sReason = "Declined Telephone Triage" Or sReason = "VISN CCC Urgent Communication" Or sReason = "VISN Clinical Contact Center Triage – Now" Or sReason = "VISN Clinical Contact Center Triage – LIP Consult/Warm Handoff" Or sReason = "Pharmacist call back" Then
            Result = "style=background-color:red;font-weight:bold;color:#ffffff;"
        ElseIf sReason = "Refused RN Recommendation" Then
            Result = "style=background-color:orange;font-weight:bold;color:#ffffff;"
        ElseIf sReason = "Medication (window pickup)" Then
            Result = "style=background-color:#ADD8E6;font-weight:bold;color:#000000;"
        ElseIf sReason = "Discharge Handoff" Then
            Result = "style=background-color:purple;font-weight:bold;color:#ffffff;"
        End If
        ReconcileReasonInlineStyle = Result
    End Function

    ' multiple Teams, sort order will be last for each Team
    Function GetLastTeamSortOrder(ti)
        ' ti = TeamIndex
        ' returns the current maximum value.  The next sort order is compted later.
        Dim sSqlString
        Dim result = 0


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        sSqlString = "SELECT MAX(tab_Members.Me_SortOrder) AS LASTSORTORDER FROM tab_Members WHERE tab_Members.Me_TeamIndex = " & ti & ";"

        MyCommand.CommandText = sSqlString

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If sqlDataReader.Read = False Then
                result = 0
            Else
                If IsDBNull(sqlDataReader.Item("LASTSORTORDER")) Then
                    result = 0
                Else
                    result = sqlDataReader.Item("LASTSORTORDER")
                End If
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        GetLastTeamSortOrder = result
    End Function

    Function StoreAuditAdmin(AA_Action, AA_Details)
        ' return "Success" or error message
        ' AA_Action = Action taken: {Add, Edit, Remove} on what: {Site, Location, Team, Member, Admins}

        ' cannot store a blank, but allow Audit anyway
        If AA_Action = "" Then
            AA_Action = "Nothing"
        End If
        If AA_Details = "" Then
            AA_Details = "Nothing"
        End If
        sSqlString = "INSERT INTO tab_AuditAdmin (AA_Action, AA_Details, AA_Dt, AA_Tm, AA_Username, AA_IP) VALUES ('" & AA_Action & "', '" & Replace(AA_Details, "'", "''")
        ' #date# for access, 'date' for sSqlString
        If _clsMessageVAR.BUsesSqlString = True Then
            sSqlString = sSqlString & "', '" & theDate & "', '" & DateTime.Now.AddHours(dTimezoneOffset) & "', '"
        Else
            sSqlString = sSqlString & "', #" & theDate & "#, #" & DateTime.Now.AddHours(dTimezoneOffset) & "#, '"
        End If
        sSqlString = sSqlString & Replace(Me.UserName, "'", "''") & "', '" & Me.UserIP & "');"

        If InsertTableRecord(sSqlString) Then
            StoreAuditAdmin = "Success"
        Else
            StoreAuditAdmin = "Error " & Err.Number & ": " & Err.Description
        End If
    End Function

    Sub ShowSetupMenu()
        ' Setup Menu
        ' ---
        ' show the tables
        ' ---


        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing
        Dim sqlDataReader2 As SqlDataReader = Nothing
        Dim sqlDataReader3 As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyConnection2 = New SqlConnection(strConn)
        Dim MyConnection3 = New SqlConnection(strConn)

        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        Dim MyCommand2 As New SqlCommand()
        MyCommand2.Connection = MyConnection2
        MyCommand2.CommandType = CommandType.Text

        Dim MyCommand3 As New SqlCommand()
        MyCommand3.Connection = MyConnection3
        MyCommand3.CommandType = CommandType.Text

        Dim sSqlString, sSqlString2
        Dim cntr = 0
        Dim cntr2 = 0
        Dim prevUsername, lastIndex, CheckType
        Dim menu

        If (Not Request.QueryString("menu") Is Nothing) Then menu = Request.QueryString("menu").ToString() Else menu = ""

        Dim really, blockSize ' used in: Purge, Parse
        Dim errstore
        Dim thecount = 0
        Dim oldName, oldEmail, oldUsername, oldActive, oldSortOrder ' used in ConsistencyCheck and EditSettings

        ' Admin = Can View and Edit all Messages.  Can Edit Setup.
        ' Site = Can View and Edit all Messages.  Cannot View or Edit Setup.
        If Me.AdminAccess = "Admin" Then
            ' GOOD
        Else
            ' prevent hacked URL
            menu = ""
        End If

        ' Setup Menu Bar:
        Response_WriteLine("<nav class=""navbar navbar-default"" style=""background-color: #dbe4f0;border:1px solid #888; box-shadow:0px 2px 5px #ccc;"">")
        Response_WriteLine("<div class=""container-fluid"">")
        Response_WriteLine("<div class=""navbar-header"">")
        Response_WriteLine("<button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
        Response_WriteLine("<span class=""sr-only"">Toggle navigation</span>")
        Response_WriteLine("<span class=""icon-bar""></span>")
        Response_WriteLine("<span class=""icon-bar""></span>")
        Response_WriteLine("<span class=""icon-bar""></span>")
        Response_WriteLine("</button>")
        Response_WriteLine("<a class=""navbar-brand"" href=""#""><b><u><i>Setup Menu:</i></u></b></a>")
        Response_WriteLine("</div>")
        Response_WriteLine("<div class=""navbar-collapse collapse"">")
        Response_WriteLine("<ul class=""nav navbar-nav"">")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Check"">")
        If menu = "Check" Then
            Response_WriteLine("<b>Consistency Check</b>")
        Else
            Response_WriteLine("Consistency Check")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Stranded"">")
        If menu = "Stranded" Then
            Response_WriteLine("<b>Stranded Messages</b>")
        Else
            Response_WriteLine("Stranded Messages")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=StrandedUsers"">")
        If menu = "StrandedUsers" Then
            Response_WriteLine("<b>Stranded Users</b>")
        Else
            Response_WriteLine("Stranded Users")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge"">")
        If menu = "Purge" Then
            Response_WriteLine("<b>Purge</b>")
        Else
            Response_WriteLine("Purge")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=ParseFullID"">")
        If menu = "ParseFullID" Then
            Response_WriteLine("<b>ParseFullID</b>")
        Else
            Response_WriteLine("ParseFullID")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=ViewAdmin"">")
        If menu = "ViewAdmin" Then
            Response_WriteLine("<b>View Admins</b>")
        Else
            Response_WriteLine("View Admins")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=ViewTeam"">")
        If menu = "ViewTeam" Then
            Response_WriteLine("<b>View Teams</b>")
        Else
            Response_WriteLine("View Teams")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=ViewMember"">")
        If menu = "ViewMember" Then
            Response_WriteLine("<b>View Members</b>")
        Else
            Response_WriteLine("View Members")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Import"">")
        If menu = "Import" Then
            Response_WriteLine("<b>Import Team</b>")
        Else
            Response_WriteLine("Import Team")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">")
        If menu = "Edit" Then
            Response_WriteLine("<b>Edit Setup</b>")
        Else
            Response_WriteLine("Edit Setup")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Audit"">")
        If menu = "Audit" Then
            Response_WriteLine("<b>View Audit</b>")
        Else
            Response_WriteLine("View Audit")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=LogFiles"">")
        If menu = "LogFiles" Then
            Response_WriteLine("<b>View Logs</b>")
        Else
            Response_WriteLine("View Logs")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=AppVar"">")
        If menu = "AppVar" Then
            Response_WriteLine("<b>View AppVar</b>")
        Else
            Response_WriteLine("View AppVar")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("<li><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=TestDelay"">")
        If menu = "TestDelay" Then
            Response_WriteLine("<b>TestDelay</b>")
        Else
            Response_WriteLine("TestDelay")
        End If
        Response_WriteLine("</a></li>")
        Response_WriteLine("</ul></div></div></nav>")
        Select Case menu


            Case "Purge"
                ' clear PII from messages > 6 months since completion
                '   FullID, LastName, FirstName, Phone, Comment, Status
                ' delete Message Index record and associated Audit records for messages > 2 years since completion

                Dim PurgeDatePII, PurgeDateAll, PurgeDateAdmin, PurgeDateHo, PurgeMSG
                ' the looped UPDATE and DELETE calls are slow.  About 100 DELETES of a message and audits per minute.
                blockSize = 500

                ' PurgeDatePII: if Today = 5/16/2012, 1st of month 6 months ago = 11/1/2011
                PurgeDatePII = DateAdd("m", -6, theDate)
                PurgeDatePII = CDate(DatePart("m", PurgeDatePII) & "/1/" & DatePart("yyyy", PurgeDatePII))

                ' PurgeDateAll: if Today = 5/16/2012, 1st of year 2 years ago = 1/1/2010
                PurgeDateAll = DateAdd("yyyy", -2, theDate)
                PurgeDateAll = CDate("1/1/" & DatePart("yyyy", PurgeDateAll))

                ' PurgeDateAdmin: if Today = 5/16/2012, 1st of month 1 year ago = 5/1/2011
                PurgeDateAdmin = DateAdd("m", -12, theDate)
                PurgeDateAdmin = CDate(DatePart("m", PurgeDateAdmin) & "/1/" & DatePart("yyyy", PurgeDateAdmin))

                ' PurgeDateHo: date of oldest open or closed message 
                PurgeDateHo = ""

                MyCommand.CommandText = "SELECT TOP 1 tab_Messages.Msg_Dt AS MINDATE FROM tab_Messages ORDER BY tab_Messages.Msg_Dt ASC;"

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = False Then
                        PurgeDateHo = CDate("1/1/2000")
                    Else
                        PurgeDateHo = sqlDataReader.Item("MINDATE")
                        If PurgeDateHo.ToString = "" Then
                            PurgeDateHo = CDate("1/1/2000")
                        Else
                            PurgeDateHo = CDate(PurgeDateHo)
                        End If
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                'Response.Write("PurgeDateHo=" & PurgeDateHo & "<br>")
                Response_WriteLine("<br>")
                Response_WriteLine("<table bgcolor=""#eeeeee""><tr><td>")
                Response_WriteLine("" & PurgeDateAll & " = ""All Purge"" Date, the 1st of the year at 2 years ago, data kept for statistics and reports<br>")
                Response_WriteLine("" & PurgeDatePII & " = ""PII Blanking"" Date, the 1st of the month at 6 months ago, data kept for provider follow-up<br>")
                If Me.AdminSite = "000" And Me.AdminAccess = "Admin" Then
                    Response_WriteLine("" & PurgeDateAdmin & " = ""Admin Audit Purge"" Date, the 1st of the month at 1 year ago, data kept for Admin changes auditing")
                    If Me.AdminType = "All" Then
                        ' only the Sytem Admin for All Types can purge Holidays
                        Response_WriteLine("<br>" & PurgeDateHo & " = ""Holiday Purge"" Date, the date of the oldest message in the system")
                    End If
                End If
                Response_WriteLine("</td></tr>")
                Response_WriteLine("<tr><td><center>Do the ""All Purge"" until there are 0 remaining, then can blank PII.</center></td></tr>")
                Response_WriteLine("</table>")
                If (Not Request.QueryString("really") Is Nothing) Then really = Request.QueryString("really").ToString() Else really = ""
                Select Case really


                    Case "AllNow"
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("Phase 2/3: View the DELETE MESSAGE candidates for ""All Closed Messages older than " & PurgeDateAll & """<br>")
                        Response_WriteLine("<b>Phase 3/3: Commit the DELETE MESSAGE action to the database</b>")
                        Response_WriteLine("</td></tr></table>")
                        ' TO DELETE MESSAGES AND AUDITS:
                        ' REQUIRES Relationship with Delete Cascade between 1 (tab_Messages) and Many (Audit)
                        ' TO DELETE MESSAGES BUT LEAVE STRANDED AUDITS:
                        ' Does not need relationship, rather follow the "purge stranded audits" sequence to clean those out
                        ' This DELETE query works wether or not the relationship exists
                        sSqlString = "DELETE FROM tab_Messages" & " WHERE EXISTS (SELECT 1" & " FROM tab_Audit WHERE tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & " AND tab_Audit.Au_Action = 'Completed'"
                        ' #date# for access, 'date' for sSqlString
                        If _clsMessageVAR.BUsesSqlString = True Then
                            sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDateAll & "')"
                        Else
                            sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDateAll & "#)"
                        End If
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND EXISTS (SELECT 1 FROM tab_Locations WHERE tab_Locations.Lo_Index = tab_Messages.Msg_LocationIndex AND tab_Locations.Lo_Type = '" & Me.AdminType & "')"
                        End If
                        If Me.AdminSite = "000" Then
                            sSqlString = sSqlString & ";"
                        Else
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "';"
                        End If
                        If _clsMessageVAR.BDebug = True Then
                            Response.Write("sSqlString=" & sSqlString & "<br>")
                        End If

                        ' increase script timeout as this can be SLOW
                        ' 600 = 60 seconds x 10 minutes
                        ' default was 90
                        Server.ScriptTimeout = 600

                        ' default timeout is 30
                        'db.CommandTimeout = 180 TODO - Do we need to refactor this? TJD

                        If DeleteTableRecords(sSqlString) Then
                            Response_WriteLine("<p><font color=""green"">DELETE MESSAGES Succeeded!</font></p>")
                        Else
                            Response_WriteLine("<p><font color=""red"">DELETE MESSAGES Failed!</font></p>")
                            Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>Purge ALLNOW: The likely reason is that sSqlString statement is buggy<br>", True, False)
                        End If
                        errstore = Me.StoreAuditAdmin("Phase 3 Purge PII", sSqlString)
                        If errstore <> "Success" Then
                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                        End If
                        Response_WriteLine("<p>Restart at <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge"">Purge</a> menu item again.<br>")
                        Response_WriteLine("See if anything is left to do.</p>")
                    Case "All"
                        ' "All" = show the index, LastName and Date of what will be deleted
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("<b>Phase 2/3: View the DELETE MESSAGE candidates for ""All Closed Messages older than " & PurgeDateAll & """</b><br>")
                        Response_WriteLine("Phase 3/3: Commit the DELETE MESSAGE action to the database")
                        Response_WriteLine("</td></tr></table>")
                        ' flush buffer before potential large loop
                        If Response.Buffer = True Then
                            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                            Response.Flush()
                        End If
                        sSqlString = "SELECT TOP " & blockSize & " tab_Messages.Msg_Index, tab_Messages.Msg_LastName, tab_Audit.Au_Dt"
                        If Me.AdminType = "All" Then
                            ' don't filter by Type
                            sSqlString = sSqlString & " FROM tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDateAll & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDateAll & "#"
                            End If
                        Else
                            sSqlString = sSqlString & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDateAll & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDateAll & "#"
                            End If
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Replace(Me.AdminType, "'", "''") & "'"
                        End If
                        If Me.AdminSite = "000" Then
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"
                        Else
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Messages.Msg_Index DESC;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                Response_WriteLine("<p>No Completed Messages Found to Purge</p>")
                            Else
                                'sqlDataReader.Read()
                                Response_WriteLine("<p><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=AllNow"">Purge Messages Now</a> <font color=""red"">WARNING: Action is not recoverable!</font></p>")
                                Response_WriteLine("<p><b>All</b> ")
                                If Me.AdminType <> "All" Then
                                    Response_WriteLine("" & Me.AdminType & "")
                                End If
                                Response_WriteLine("Closed ")
                                Response_WriteLine("Messages")
                                If Me.AdminSite <> "000" Then
                                    Response_WriteLine("for <b>Site " & Me.AdminSite & "</b>")
                                End If
                                Response_WriteLine("Purge Date " & PurgeDatePII & ":<br>")
                                Response_WriteLine("(Sample is up to the most recent " & blockSize & " that will be purged)<br>")
                                Response_WriteLine("<br>")
                                Response_WriteLine("<table>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td>Index</td><td>Last Name</td><td>Close Date</td></tr>")
                                lastIndex = 0
                                While sqlDataReader.Read = True And cntr <= blockSize
                                    If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                        ' skip, duplicate Audit records make for repeat rows
                                    Else
                                        Response_WriteLine("<tr><td>" & sqlDataReader.Item("Msg_Index") & "</td><td>" & sqlDataReader.Item("Msg_LastName") & "</td><td>" & sqlDataReader.Item("Au_Dt") & "</td></tr>")
                                        cntr = cntr + 1
                                    End If
                                    lastIndex = sqlDataReader.Item("Msg_Index")
                                End While
                                Response_WriteLine("<tr><td colspan=""3""><center>...End of list of " & cntr & " candidates...</center></td></tr>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</p>")
                                errstore = Me.StoreAuditAdmin("Phase 2 Purge All", sSqlString)
                                If errstore <> "Success" Then
                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Case "PIINow"
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("Phase 2/3: View the PII BLANKING candidates for ""All Closed Messages older than " & PurgeDatePII & """<br>")
                        Response_WriteLine("<b>Phase 3/3: Commit the PII BLANKING action to the database</b>")
                        Response_WriteLine("</td></tr></table>")
                        ' retain SiteNum, LocationIndex, TeamIndex, Completed, Assigned, EmailSent, Reason, Dt, Tm, Username, IP
                        sSqlString = "UPDATE tab_Messages SET" & " tab_Messages.Msg_FullID = NULL, tab_Messages.Msg_FirstName = NULL, tab_Messages.Msg_LastName = NULL, tab_Messages.Msg_LastFour = NULL, tab_Messages.Msg_DOB = NULL," & " tab_Messages.Msg_Phone = NULL, tab_Messages.Msg_ReturnCall = NULL, tab_Messages.Msg_BestTime = NULL," & " tab_Messages.Msg_VendorName = NULL, tab_Messages.Msg_VendorContactInfo = NULL, tab_Messages.Msg_VendorTaxID = NULL," & " tab_Messages.Msg_MedChoice = NULL, tab_Messages.Msg_Status = NULL, tab_Messages.Msg_Comment = NULL" & " WHERE EXISTS (SELECT 1" & " FROM tab_Audit WHERE tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & " AND tab_Audit.Au_Action = 'Completed'"
                        ' #date# for access, 'date' for sSqlString
                        If _clsMessageVAR.BUsesSqlString = True Then
                            sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDatePII & "')"
                        Else
                            sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDatePII & "#)"
                        End If
                        If Me.AdminType <> "All" Then
                            sSqlString = sSqlString & " AND EXISTS (SELECT 1 FROM tab_Locations WHERE tab_Locations.Lo_Index = tab_Messages.Msg_LocationIndex AND tab_Locations.Lo_Type = '" & Me.AdminType & "')"
                        End If
                        ' tab_Messages.Msg_Phone IS NOT NULL --- that only updates messages that have been previously purged.
                        If Me.AdminSite = "000" Then
                            sSqlString = sSqlString & " AND tab_Messages.Msg_Phone IS NOT NULL;"
                        Else
                            sSqlString = sSqlString & " AND tab_Messages.Msg_Phone IS NOT NULL AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "';"
                        End If

                        ' increase script timeout as this can be SLOW
                        ' 600 = 60 seconds x 10 minutes
                        ' default was 90
                        Server.ScriptTimeout = 600

                        ' default timeout is 30
                        'db.CommandTimeout = 180 TODO - Do we need to refactor this? TJD

                        'On Error Resume Next

                        If UpdateTableRecords(sSqlString) Then
                            Response_WriteLine("<p><font color=""green"">PII BLANKING Succeeded!</font></p>")
                        Else
                            Response_WriteLine("<p><font color=""red"">PII BLANKING Failed!</font></p>")
                            Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>Purge PIINOW: The likely reason is that sSqlString statement is buggy<br>", True, False)
                        End If
                        errstore = Me.StoreAuditAdmin("Phase 3 Purge PII", sSqlString)
                        If errstore <> "Success" Then
                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                        End If
                        Response_WriteLine("<p>Restart at <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge"">Purge</a> menu item again.<br>")
                        Response_WriteLine("See if anything is left to do.</p>")

                    Case "PII"
                        ' "PII" = show the index of what will be emptied
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("<b>Phase 2/3: View the PII BLANKING candidates for ""All Closed Messages older than " & PurgeDatePII & """</b><br>")
                        Response_WriteLine("Phase 3/3: Commit the PII BLANKING action to the database")
                        Response_WriteLine("</td></tr></table>")
                        ' flush buffer before potential large loop
                        If Response.Buffer = True Then
                            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                            Response.Flush()
                        End If
                        sSqlString = "SELECT TOP " & blockSize & " tab_Messages.Msg_Index, tab_Messages.Msg_LastName, tab_Audit.Au_Dt"
                        ' tab_Messages.Msg_Phone IS NOT NULL... is used because:
                        '    it eliminates data that was already purged
                        '    Phone is a required field so is guaranteed to have something
                        If Me.AdminType = "All" Then
                            ' don't limit
                            sSqlString = sSqlString & " FROM tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage" & " WHERE tab_Messages.Msg_Phone IS NOT NULL" & " AND tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDatePII & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDatePII & "#"
                            End If
                        Else
                            sSqlString = sSqlString & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage)" & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_Phone IS NOT NULL" & " AND tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDatePII & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDatePII & "#"
                            End If
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Replace(Me.AdminType, "'", "''") & "'"
                        End If
                        If Me.AdminSite = "000" Then
                            sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"
                        Else
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Messages.Msg_Index DESC;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                Response_WriteLine("<p>No Completed Messages found to PII Blank</p>")
                            Else
                                'sqlDataReader.Read()
                                Response_WriteLine("<p><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=PIINow"">Blank PII Now</a> <font color=""red"">WARNING: Action is not recoverable!</font></p>")
                                Response_WriteLine("<p><b>PII</b> ")
                                If Me.AdminType <> "All" Then
                                    Response_WriteLine("" & Me.AdminType & "")
                                End If
                                Response_WriteLine("Closed ")
                                Response_WriteLine("Messages")
                                If Me.AdminSite <> "000" Then
                                    Response_WriteLine("for <b>Site " & Me.AdminSite & "</b>")
                                End If
                                Response_WriteLine("Purge Date " & PurgeDatePII & ":<br>")
                                Response_WriteLine("(Sample is up to the most recent " & blockSize & " that will be purged)<br>")
                                Response_WriteLine("<br>")
                                Response_WriteLine("<table>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td>Index</td><td>LastName</td><td>Close Date</td></tr>")
                                lastIndex = 0
                                While sqlDataReader.Read = True And cntr <= blockSize
                                    If lastIndex = sqlDataReader.Item("Msg_Index") Then
                                        ' skip, duplicate Audit records make for repeat rows
                                    Else
                                        Response_WriteLine("<tr><td>" & sqlDataReader.Item("Msg_Index") & "</td><td>" & sqlDataReader.Item("Msg_LastName") & "</td><td>" & sqlDataReader.Item("Au_Dt") & "</td></tr>")
                                        cntr = cntr + 1
                                    End If
                                    lastIndex = sqlDataReader.Item("Msg_Index")
                                End While
                                Response_WriteLine("<tr><td colspan=""2"">...End of list of " & cntr & " candidates...</td></tr>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</p>")
                                errstore = Me.StoreAuditAdmin("Phase 2 Purge PII", sSqlString)
                                If errstore <> "Success" Then
                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Case "AdminNow"
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("Phase 2/3: View the DELETE AUDIT candidates for ""All Admin Aduits older than " & PurgeDateAdmin & """<br>")
                        Response_WriteLine("<b>Phase 3/3: Commit the DELETE AUDIT action to the database</b>")
                        Response_WriteLine("</td></tr></table>")
                        ' #date# for access, 'date' for sSqlString
                        If _clsMessageVAR.BUsesSqlString = True Then
                            sSqlString = "DELETE FROM tab_AuditAdmin WHERE tab_AuditAdmin.AA_Dt < '" & PurgeDateAdmin & "';"
                        Else
                            sSqlString = "DELETE FROM tab_AuditAdmin WHERE tab_AuditAdmin.AA_Dt < #" & PurgeDateAdmin & "#;"
                        End If

                        If DeleteTableRecords(sSqlString) Then
                            Response_WriteLine("<p><font color=""green"">DELETE ADMIN AUDIT Succeeded!</font></p>")
                        Else
                            Response_WriteLine("<p><font color=""red"">DELETE ADMIN AUDIT Failed!</font></p>")
                            Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>Purge ADMINNOW: The likely reason is that sSqlString statement is buggy<br>", True, False)
                        End If
                        errstore = Me.StoreAuditAdmin("Phase 3 Purge AdminAudit", sSqlString)
                        If errstore <> "Success" Then
                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                        End If
                        Response_WriteLine("<p>Restart at <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge"">Purge</a> menu item again.<br>")
                        Response_WriteLine("See if anything is left to do.</p>")
                    Case "Admin"
                        ' "Admin" = show the AA_Action and Date of what will be deleted
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("<b>Phase 2/3: View the DELETE AUDIT candidates for ""All Admin Aduits older than " & PurgeDateAdmin & """</b><br>")
                        Response_WriteLine("Phase 3/3: Commit the DELETE AUDIT action to the database")
                        Response_WriteLine("</td></tr></table>")
                        ' flush buffer before potential large loop
                        If Response.Buffer = True Then
                            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                            Response.Flush()
                        End If
                        sSqlString = "SELECT TOP " & blockSize & " tab_AuditAdmin.AA_Action, tab_AuditAdmin.AA_Dt FROM tab_AuditAdmin"
                        ' #date# for access, 'date' for sSqlString
                        If _clsMessageVAR.BUsesSqlString = True Then
                            sSqlString = sSqlString & " WHERE tab_AuditAdmin.AA_Dt < '" & PurgeDateAdmin & "'"
                        Else
                            sSqlString = sSqlString & " WHERE tab_AuditAdmin.AA_Dt < #" & PurgeDateAdmin & "#"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_AuditAdmin.AA_Dt, tab_AuditAdmin.AA_Tm;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                Response_WriteLine("<p>No Admin Audits Found to Purge</p>")
                            Else
                                'sqlDataReader.Read()
                                Response_WriteLine("<p><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=AdminNow"">Purge Admin Audits Now</a> <font color=""red"">WARNING: Action is not recoverable!</font></p>")
                                Response_WriteLine("<p>Admin Audit Purge Date " & PurgeDateAdmin & ":<br>")
                                Response_WriteLine("(Sample is up to the first " & blockSize & " that will be purged)<br>")
                                Response_WriteLine("<br>")
                                Response_WriteLine("<table>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td>Action</td><td>Date</td></tr>")
                                cntr = 0
                                While sqlDataReader.Read = True And cntr <= blockSize
                                    Response_WriteLine("<tr><td>" & sqlDataReader.Item("AA_Action") & "</td><td>" & sqlDataReader.Item("AA_Dt") & "</td></tr>")
                                    cntr = cntr + 1
                                End While
                                Response_WriteLine("<tr><td colspan=""2""><center>...End of list of " & cntr & " candidates...</center></td></tr>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</p>")
                                errstore = Me.StoreAuditAdmin("Phase 2 Purge AdminAudit", sSqlString)
                                If errstore <> "Success" Then
                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Case "HolidayNow"
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("Phase 2/3: View the DELETE HOLIDAY candidates for ""All Holidays older than " & PurgeDateHo & """<br>")
                        Response_WriteLine("<b>Phase 3/3: Commit the DELETE Holiday action to the database</b>")
                        Response_WriteLine("</td></tr></table>")
                        ' #date# for access, 'date' for sSqlString
                        If _clsMessageVAR.BUsesSqlString = True Then
                            sSqlString = "DELETE FROM tab_Holidays WHERE tab_Holidays.Ho_Date < '" & PurgeDateHo & "';"
                        Else
                            sSqlString = "DELETE FROM tab_Holidays WHERE tab_Holidays.Ho_Date < #" & PurgeDateHo & "#;"
                        End If

                        If DeleteTableRecords(sSqlString) Then
                            Response_WriteLine("<p><font color=""green"">DELETE HOLIDAY Succeeded!</font></p>")
                        Else
                            Response_WriteLine("<p><font color=""red"">DELETE HOLIDAY Failed!</font></p>")
                            Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>Purge HOLIDAYNOW: The likely reason is that sSqlString statement is buggy<br>", True, False)
                        End If
                        errstore = Me.StoreAuditAdmin("Phase 3 Purge Holiday", sSqlString)
                        If errstore <> "Success" Then
                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                        End If
                        ' reset Application Variable to force Holiday reload
                        Application("Ho.CrDate") = DateAdd("d", -1, theDate)
                        Response_WriteLine("<p>Restart at <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge"">Purge</a> menu item again.<br>")
                        Response_WriteLine("See if anything is left to do.</p>")
                    Case "Holiday"
                        ' "Holiday" = show the Ho_Date and Ho_Name of what will be deleted
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("<b>Phase 2/3: View the DELETE HOLIDAY candidates for ""All Holidays older than " & PurgeDateHo & """</b><br>")
                        Response_WriteLine("Phase 3/3: Commit the DELETE HOLIDAY action to the database")
                        Response_WriteLine("</td></tr></table>")
                        ' flush buffer before potential large loop
                        If Response.Buffer = True Then
                            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                            Response.Flush()
                        End If
                        ' not using "TOP blocksize" for holidays as the number is always small enough
                        sSqlString = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays"
                        ' #date# for access, 'date' for sSqlString
                        If _clsMessageVAR.BUsesSqlString = True Then
                            sSqlString = sSqlString & " WHERE tab_Holidays.Ho_Date < '" & PurgeDateHo & "'"
                        Else
                            sSqlString = sSqlString & " WHERE tab_Holidays.Ho_Date < #" & PurgeDateHo & "#"
                        End If
                        sSqlString = sSqlString & " ORDER BY tab_Holidays.Ho_Date;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                Response_WriteLine("<p>No Holidays Found to Purge</p>")
                            Else
                                'sqlDataReader.Read()
                                Response_WriteLine("<p><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=HolidayNow"">Purge Holidays Now</a> <font color=""red"">WARNING: Action is not recoverable!</font></p>")
                                Response_WriteLine("<p>Holiday Purge Date " & PurgeDateHo & ":<br>")
                                Response_WriteLine("<br>")
                                Response_WriteLine("<table>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td>Date</td><td>Name</td></tr>")
                                cntr = 0
                                While sqlDataReader.Read = True
                                    Response_WriteLine("<tr><td>" & sqlDataReader.Item("Ho_Date") & "</td><td>" & sqlDataReader.Item("Ho_Name") & "</td></tr>")
                                    cntr = cntr + 1
                                End While
                                Response_WriteLine("<tr><td colspan=""2""><center>...End of list of " & cntr & " candidates...</center></td></tr>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</p>")
                                errstore = Me.StoreAuditAdmin("Phase 2 Purge Holiday", sSqlString)
                                If errstore <> "Success" Then
                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Case "StrandedNow"
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("Phase 2/3: View the DELETE STRANDED AUDITS candidates<br>")
                        Response_WriteLine("<b>Phase 3/3: Commit the DELETE STRANDED AUDITS action to the database</b>")
                        Response_WriteLine("</td></tr></table>")
                        sSqlString = "DELETE FROM tab_Audit WHERE Au_IndexMessage IN " & "(SELECT Au_IndexMessage FROM" & " tab_Audit LEFT JOIN tab_Messages ON tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & " WHERE tab_Messages.Msg_Index Is Null);"

                        ' increase script timeout as this can be SLOW
                        ' 600 = 60 seconds x 10 minutes
                        ' default was 90
                        Server.ScriptTimeout = 600

                        ' default timeout is 30
                        'db.CommandTimeout = 90 TODO - Do we need to refactor this? TJD

                        If DeleteTableRecords(sSqlString) Then
                            Response_WriteLine("<p><font color=""green"">DELETE STRANDED AUDITS Succeeded!</font></p>")
                        Else
                            Response_WriteLine("<p><font color=""red"">DELETE STRANDED AUDITS Failed!</font></p>")
                            Me.ErrorHandler(Err.Number & ": " & Err.Description & "<br><br>" & sSqlString & "<br><br>Purge STRANDED AUDITS NOW: The likely reason is that sSqlString statement is buggy<br>", True, False)
                        End If
                        errstore = Me.StoreAuditAdmin("Phase 3 Purge Holiday", sSqlString)
                        If errstore <> "Success" Then
                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                        End If
                        ' reset Application Variable to force Holiday reload
                        Application("Ho.CrDate") = DateAdd("d", -1, theDate)
                        Response_WriteLine("<p>Restart at <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge"">Purge</a> menu item again.<br>")
                        Response_WriteLine("See if anything is left to do.</p>")
                    Case "Stranded"
                        ' "Stranded" = show the tab_Audit.Au_MessageIndex of what will be deleted
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("Phase 1/3: View counts for purge categories<br>")
                        Response_WriteLine("<b>Phase 2/3: View the DELETE STRANDED AUDITS candidates</b><br>")
                        Response_WriteLine("Phase 3/3: Commit the DELETE STRANDED AUDITS action to the database")
                        Response_WriteLine("</td></tr></table>")
                        ' flush buffer before potential large loop
                        If Response.Buffer = True Then
                            'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                            Response.Flush()
                        End If
                        'sSqlString = "SELECT DISTINCT(tab_Audit.Au_IndexMessage) AS DISINDEX" & '	" FROM tab_Audit LEFT JOIN tab_Messages ON tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & '	" WHERE tab_Messages.Msg_Index Is Null;"
                        sSqlString = "SELECT DISTINCT(Au_IndexMessage) FROM tab_Audit" & " WHERE Au_IndexMessage IN" & " (SELECT Au_IndexMessage FROM" & " tab_Audit LEFT JOIN tab_Messages ON tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & " WHERE tab_Messages.Msg_Index Is Null);"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If Not sqlDataReader.HasRows Then
                                Response_WriteLine("<p>No ""Stranded Audits"" Found to Purge</p>")
                            Else
                                Response_WriteLine("<p><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=StrandedNow"">Purge Stranded Audits Now</a> <font color=""red"">WARNING: Action is not recoverable!</font></p>")
                                Response_WriteLine("<p>Message Index of Stranded Audits:<br>")
                                Response_WriteLine("<br>")
                                cntr = 0
                                While sqlDataReader.Read = True
                                    If cntr = 0 Then
                                        Response.Write(sqlDataReader.Item("Au_IndexMessage"))
                                    Else
                                        Response.Write(", " & sqlDataReader.Item("Au_IndexMessage"))
                                    End If
                                    cntr = cntr + 1
                                End While
                                Response_WriteLine("<br>")
                                Response_WriteLine("...End of list of " & cntr & " candidates...")
                                Response_WriteLine("</p>")
                                errstore = Me.StoreAuditAdmin("Phase 2 Purge Holiday", sSqlString)
                                If errstore <> "Success" Then
                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                End If
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    Case Else
                        PurgeMSG = ""
                        Response_WriteLine("<table><tr><td>")
                        Response_WriteLine("<b>Phase 1/3: View counts for purge categories</b><br>")
                        Response_WriteLine("Phase 2/3: View the Index list for chosen purge category<br>")
                        Response_WriteLine("Phase 3/3: Commit the purge to the database")
                        Response_WriteLine("</td></tr></table>")
                        ' Show ALL PURGE first
                        sSqlString = "SELECT COUNT(tab_derived_Msg.Msg_Index) AS THECOUNT FROM ("
                        If Me.AdminType = "All" Then
                            ' don't limit
                            sSqlString = sSqlString & " SELECT tab_Messages.Msg_Index" & " FROM tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage " & " WHERE tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDateAll & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDateAll & "#"
                            End If
                        Else
                            sSqlString = sSqlString & " SELECT tab_Messages.Msg_Index" & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage) " & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDateAll & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDateAll & "#"
                            End If
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Replace(Me.AdminType, "'", "''") & "'"
                        End If
                        If Me.AdminSite = "000" Then
                            sSqlString = sSqlString & ") AS tab_derived_Msg;"
                        Else
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "') AS tab_derived_Msg;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = True Then
                                thecount = sqlDataReader.Item("THECOUNT")
                                PurgeMSG = PurgeMSG & "<p>There are " & thecount & " "
                                If Me.AdminType <> "All" Then
                                    PurgeMSG = PurgeMSG & Me.AdminType & " "
                                End If
                                PurgeMSG = PurgeMSG & "messages "
                                If Me.AdminSite <> "000" Then
                                    PurgeMSG = PurgeMSG & "for Site " & Me.AdminSite & " "
                                End If
                                PurgeMSG = PurgeMSG & "that are candidates for Message and Audit removal.<br>"
                                If thecount > 0 Then
                                    PurgeMSG = PurgeMSG & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=All"">View ""All Purge"" Candidates</a>"
                                Else
                                    PurgeMSG = PurgeMSG & "<font color=""green"">No messages to delete!  Try again another year.</font>"
                                End If
                                PurgeMSG = PurgeMSG & "</p>"
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        errstore = Me.StoreAuditAdmin("Phase 1 Purge All", sSqlString)
                        If errstore <> "Success" Then
                            PurgeMSG = PurgeMSG & "<p><font color=""red"">" & errstore & "</font></p>"
                        End If
                        Response.Write(PurgeMSG)
                        PurgeMSG = ""

                        ' preserve the value for use after the next query results
                        cntr = thecount

                        ' Show PII BLANK last
                        ' tab_Messages.Msg_Phone IS NOT NULL... is used because it eliminates data that was already purged
                        sSqlString = "SELECT COUNT(tab_derived_Msg.Msg_Index) AS THECOUNT FROM (SELECT DISTINCT(tab_Messages.Msg_Index)"
                        If Me.AdminType = "All" Then
                            ' don't limit
                            sSqlString = sSqlString & " FROM tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage " & " WHERE tab_Messages.Msg_Phone IS NOT NULL" & " AND tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDatePII & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDatePII & "#"
                            End If
                        Else
                            sSqlString = sSqlString & " FROM (tab_Messages LEFT JOIN tab_Audit ON tab_Messages.Msg_Index = tab_Audit.Au_IndexMessage) " & " LEFT JOIN tab_Locations ON tab_Messages.Msg_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Messages.Msg_Phone IS NOT NULL" & " AND tab_Audit.Au_Action = 'Completed'"
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < '" & PurgeDatePII & "'"
                            Else
                                sSqlString = sSqlString & " AND tab_Audit.Au_Dt < #" & PurgeDatePII & "#"
                            End If
                            sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Replace(Me.AdminType, "'", "''") & "'"
                        End If
                        If Me.AdminSite = "000" Then
                            sSqlString = sSqlString & ") AS tab_derived_Msg;"
                        Else
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "') AS tab_derived_Msg;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = True Then
                                thecount = sqlDataReader.Item("THECOUNT")
                                PurgeMSG = PurgeMSG & "<p>There are " & thecount & " "
                                If Me.AdminType <> "All" Then
                                    PurgeMSG = PurgeMSG & Me.AdminType & " "
                                End If
                                PurgeMSG = PurgeMSG & "messages "
                                If Me.AdminSite <> "000" Then
                                    PurgeMSG = PurgeMSG & "for Site " & Me.AdminSite & " "
                                End If
                                PurgeMSG = PurgeMSG & "that are candidates for PII blanking.<br>"
                                If thecount > 0 Then
                                    If cntr > 0 Then
                                        PurgeMSG = PurgeMSG & "<font color=""red"">Cannot purge PII data until the ""All Purge"" category has completed.</font>"
                                    Else
                                        PurgeMSG = PurgeMSG & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=PII"">View ""PII Blank"" Candidates</a>"
                                    End If
                                Else
                                    PurgeMSG = PurgeMSG & "<font color=""green"">No PII to blank out!  Try again another month.</font>"
                                End If
                                PurgeMSG = PurgeMSG & "</p>"
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        errstore = Me.StoreAuditAdmin("Phase 1 Purge PII", sSqlString)
                        If errstore <> "Success" Then
                            PurgeMSG = PurgeMSG & "<p><font color=""red"">" & errstore & "</font></p>"
                        End If
                        Response.Write(PurgeMSG)
                        PurgeMSG = ""

                        ' Show Admin Audit purge
                        If Me.AdminSite = "000" And Me.AdminAccess = "Admin" Then
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = "SELECT COUNT(tab_AuditAdmin.AA_Action) AS THECOUNT FROM tab_AuditAdmin WHERE tab_AuditAdmin.AA_Dt < '" & PurgeDateAdmin & "';"
                            Else
                                sSqlString = "SELECT COUNT(tab_AuditAdmin.AA_Action) AS THECOUNT FROM tab_AuditAdmin WHERE tab_AuditAdmin.AA_Dt < #" & PurgeDateAdmin & "#;"
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If sqlDataReader.Read = True Then
                                    thecount = sqlDataReader.Item("THECOUNT")
                                    PurgeMSG = PurgeMSG & "<p>There are " & thecount & " Admin Audit entries that are candidates for Purging.<br>"
                                    If thecount > 0 Then
                                        PurgeMSG = PurgeMSG & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=Admin"">View ""Admin Audit Purge"" Candidates</a>"
                                    Else
                                        PurgeMSG = PurgeMSG & "<font color=""green"">No Admin Audits to blank out!  Try again another month.</font>"
                                    End If
                                    PurgeMSG = PurgeMSG & "</p>"
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            errstore = Me.StoreAuditAdmin("Phase 1 Purge AdminAudit", sSqlString)
                            If errstore <> "Success" Then
                                PurgeMSG = PurgeMSG & "<p><font color=""red"">" & errstore & "</font></p>"
                            End If
                        End If
                        Response.Write(PurgeMSG)
                        PurgeMSG = ""

                        ' Show Holiday Audit purge
                        If Me.AdminSite = "000" And Me.AdminAccess = "Admin" And Me.AdminType = "All" Then
                            ' #date# for access, 'date' for sSqlString
                            If _clsMessageVAR.BUsesSqlString = True Then
                                sSqlString = "SELECT COUNT(tab_Holidays.Ho_Date) AS THECOUNT FROM tab_Holidays WHERE tab_Holidays.Ho_Date < '" & PurgeDateHo & "';"
                            Else
                                sSqlString = "SELECT COUNT(tab_Holidays.Ho_Date) AS THECOUNT FROM tab_Holidays WHERE tab_Holidays.Ho_Date < #" & PurgeDateHo & "#;"
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If sqlDataReader.Read = True Then
                                    thecount = sqlDataReader.Item("THECOUNT")
                                    PurgeMSG = PurgeMSG & "<p>There are " & thecount & " non-referenced Holidays that are candidates for Purging.<br>"
                                    If thecount > 0 Then
                                        PurgeMSG = PurgeMSG & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=Holiday"">View ""Holiday Purge"" Candidates</a>"
                                    Else
                                        PurgeMSG = PurgeMSG & "<font color=""green"">No non-referenced Holidays to delete!  Try again another year.</font>"
                                    End If
                                    PurgeMSG = PurgeMSG & "</p>"
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            errstore = Me.StoreAuditAdmin("Phase 1 Purge Holiday", sSqlString)
                            If errstore <> "Success" Then
                                PurgeMSG = PurgeMSG & "<p><font color=""red"">" & errstore & "</font></p>"
                            End If
                        End If
                        Response.Write(PurgeMSG)
                        PurgeMSG = ""

                        ' find unmatched Audit entries
                        ' they would exist if messages were deleted without deleting an Audit record
                        sSqlString = "SELECT COUNT(DISTINCT(tab_Audit.Au_IndexMessage)) AS THECOUNT" & " FROM tab_Audit LEFT JOIN tab_Messages ON tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & " WHERE tab_Messages.Msg_Index Is Null;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.Read = True Then
                                thecount = sqlDataReader.Item("THECOUNT")
                                PurgeMSG = PurgeMSG & "<p>There are " & thecount & " distinct Audit Indexes w/o matching Messages.<br>"
                                If thecount > 0 Then
                                    PurgeMSG = PurgeMSG & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Purge&really=Stranded"">View ""Stranded Audit Purge"" Candidates</a>"
                                Else
                                    PurgeMSG = PurgeMSG & "<font color=""green"">No Stranded Audits to delete!  Try again another year.</font>"
                                End If
                                PurgeMSG = PurgeMSG & "</p>"
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        errstore = Me.StoreAuditAdmin("Phase 1 Purge Stranded Audits", sSqlString)
                        If errstore <> "Success" Then
                            PurgeMSG = PurgeMSG & "<p><font color=""red"">" & errstore & "</font></p>"
                        End If
                        Response.Write(PurgeMSG)
                        PurgeMSG = ""

                End Select

            Case "LogFiles"
                ' get list of log files and hyperlink them for viewing

                ' test the write first
                'StoreToLog("TEST write to Logfile, admin viewing is in action.")

                ' display list of log files
                'On Error Resume Next
                Dim fso, mappath, folder, files, file, strOutput

                mappath = Server.MapPath(".")
                ' "d:\wwwroot\Message\MessageAdmin"
                ' end result "d:\wwwroot\Message\MessageAdmin\logs"
                mappath = mappath & "\logs\"
                strOutput = ""

                fso = Vb6.CreateObject("Scripting.FileSystemObject")
                folder = fso.GetFolder(mappath)
                files = folder.Files
                For Each file In files
                    ' ";" & file.DateCreated & ";" & file.DateLastModified
                    strOutput = strOutput & "<a href=""logs\" & file.Name & """>" & file.Name & "</a><br>" & vbCrLf
                Next
                files = Nothing
                folder = Nothing
                fso = Nothing
                'On Error GoTo 0
                If strOutput = "" Then
                    Response_WriteLine("<div class=""container-fluid""><div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;""><p>No Error Logs exist</p></div></div>")
                Else
                    Response_WriteLine("<div class=""container-fluid""><div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;""><p>" & strOutput & "</p></div></div>")
                End If

            Case "AppVar"
                ' list the Application Variables
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                Response_WriteLine("<table border=""0"" cellpadding=""0"" cellspacing=""0"">")
                Response_WriteLine("<tr valign=""top"">")
                Response_WriteLine("<td width=""150""><b>Variable Name</b></td>")
                Response_WriteLine("<td width=""600""><b>Value</b></td>")
                Response_WriteLine("</tr>")
                Dim appitem
                For Each appitem In Application.Contents
                    Response_WriteLine("<tr valign=""top"">")
                    Response_WriteLine("<td align=""left""><font size=""1"">" & appitem & "</font></td>")
                    Response_WriteLine("<td align=""left""><font size=""1"">" & Application.Contents(appitem) & "</font></td>")
                    Response_WriteLine("</tr>")
                Next
                Response_WriteLine("</table></div></div>")

            Case "TestDelay"
                Dim TheDelay
                ' ComputeDelay( CDt, CTm, ADt, ADm, {"BH"|"Weekdays"|"All"} )
                ' ComputeDelayIncludeWeekends(SD, ST, ED, ET)
                Response_WriteLine("<div class=""container-fluid"">")
                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;""><p><table><tr><td>")
                Response_WriteLine("""5/8/2012"", ""8:00:00 AM"", ""5/8/2012"", ""5:00:00 PM""<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "8:00:00 AM", "5/8/2012", "5:00:00 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "8:00:00 AM", "5/8/2012", "5:00:00 PM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "8:00:00 AM", "5/8/2012", "5:00:00 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "7:58:30 AM", "5/8/2012", "5:00:00 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "7:58:30 AM", "5/8/2012", "5:00:00 PM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "7:58:30 AM", "5/8/2012", "5:00:00 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "8:00:00 AM", "5/8/2012", "5:01:30 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "8:00:00 AM", "5/8/2012", "5:01:30 PM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/8/2012", "8:00:00 AM", "5/8/2012", "5:01:30 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "12:00:00 PM", "5/8/2012", "12:00:00 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "12:00:00 PM", "5/8/2012", "12:00:00 PM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "12:00:00 PM", "5/8/2012", "12:00:00 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "06:56:00 PM", "5/8/2012", "07:58:02 AM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "06:56:00 PM", "5/8/2012", "07:58:02 AM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "06:56:00 PM", "5/8/2012", "07:58:02 AM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "6:30:00 AM", "5/9/2012", "6:30:00 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "6:30:00 AM", "5/9/2012", "6:30:00 PM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "6:30:00 AM", "5/9/2012", "6:30:00 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekday hours<br><br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "6:30:00 PM", "5/9/2012", "6:30:00 AM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "6:30:00 PM", "5/9/2012", "6:30:00 AM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "6:30:00 PM", "5/9/2012", "6:30:00 AM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "9:30:00 AM", "5/9/2012", "3:30:00 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "9:30:00 AM", "5/9/2012", "3:30:00 PM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/7/2012", "9:30:00 AM", "5/9/2012", "3:30:00 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/4/2012", "03:00:00 PM", "5/7/2012", "09:00:00 AM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/4/2012", "03:00:00 PM", "5/7/2012", "09:00:00 AM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/4/2012", "03:00:00 PM", "5/7/2012", "09:00:00 AM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "6/1/2012", "09:00:00 AM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "6/1/2012", "09:00:00 AM", "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "6/1/2012", "09:00:00 AM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "5/25/2012", "09:33:33 AM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " clock h:mm<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "5/25/2012", "10:15:00 AM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " clock h:mm<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "5/25/2012", "09:55:55 PM", "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " clock h:mm<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "09:00:00 AM", "5/25/2012", "09:55:55 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " business hours clock h:mm<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "05:05:08 AM", "5/25/2012", "07:28:25 AM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " business hours clock h:mm<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "05:05:08 PM", "5/25/2012", "10:28:25 PM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " business hours clock h:mm<br><br>")
                TheDelay = Me.ComputeDelay("5/25/2012", "05:05:08 PM", "5/26/2012", "07:28:25 AM", "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundClock(TheDelay) & " business hours clock h:mm<br><br>")
                Response_WriteLine(DateAdd("d", -7, theDate) & " 7 Day span to Now()<br><br>")
                Response_WriteLine(", " & DateTime.Now.AddHours(dTimezoneOffset) & ", " & theDate & ", " & DateTime.Now.AddHours(dTimezoneOffset) & "<br>")
                TheDelay = Me.ComputeDelay(DateAdd("d", -7, theDate), DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), theDate, DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), "BH")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " BH<br>")
                TheDelay = Me.ComputeDelay(DateAdd("d", -7, theDate), DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), theDate, DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), "Weekdays")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Weekdays<br>")
                TheDelay = Me.ComputeDelay(DateAdd("d", -7, theDate).ToString("MM/dd/yyyy"), DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), theDate.ToString("MM/dd/yyyy"), DateTime.Now.AddHours(dTimezoneOffset).ToString("HH:mm:ss"), "All")
                Response_WriteLine("(" & TheDelay & ") " & Me.roundit(TheDelay, 2) & " Day hours<br><br></td></tr></table></p></div></div>")

            Case "Recycle"
                ' hidden Setup Menu menu ' 
                ' http://message.madison.med.va.gov/MessageAdmin/Message.asp?A=Setup&S=&menu=Recycle
                ' to recycle the app pool
                _clsMessageVAR.ResetAppPool()

            Case "ParseFullID"
                ' SHOW ONLY:
                '	http://message.madison.med.va.gov/MessageAdmin/Message.asp?A=Setup&S=&menu=ParseFullID&begin=1
                ' DO THE PARSE TO DATABASE:
                '	http://message.madison.med.va.gov/MessageAdmin/Message.asp?A=Setup&S=&menu=ParseFullID&begin=1&really=Yes
                ' Note: "&begin=1 refers to the starting index, in case one wants to exclude "stuck" records

                ' temporary function 4-27-2012
                ' loop through all Index falues where FullID IS NOT NULL
                ' parse sqlDataReader.Item(fullid)
                ' if sqlDataReader.Item(firstname) IS NULL then store gFirst into it
                ' if sqlDataReader.Item(lastname) IS NULL then store glast into it
                ' if sqlDataReader.Item(lastfour) IS NULL then store gSSN into it

                Dim begin = ""
                If (Not Request.QueryString("really") Is Nothing) Then really = Request.QueryString("really").ToString() Else really = ""
                If (Not Request.QueryString("begin") Is Nothing) Then begin = Request.QueryString("begin").ToString() Else begin = ""
                If begin = "" Then
                    begin = 1
                End If
                If Not IsNumeric(begin) Then
                    begin = 1
                End If
                cntr = 0

                ' increase script timeout as this can be SLOW
                ' 600 = 60 seconds x 10 minutes
                ' default was 90
                Server.ScriptTimeout = 600

                ' flush buffer before potential large loop
                If Response.Buffer = True Then
                    'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                    Response.Flush()
                End If
                ' 1000 takes 2 seconds
                ' 2000 takes 3 seconds
                ' 3000 takes 5 seconds
                ' 4000 and more times out. ??? why ???
                blockSize = 1000
                sSqlString = "SELECT TOP " & blockSize & " tab_Messages.Msg_Index, tab_Messages.Msg_FullID, tab_Messages.Msg_FirstName, tab_Messages.Msg_LastName, tab_Messages.Msg_LastFour, tab_Messages.Msg_DOB" & " FROM tab_Messages" & " WHERE tab_Messages.Msg_FullID IS NOT NULL AND tab_Messages.Msg_Index >= " & begin & " AND (tab_Messages.Msg_FirstName IS NULL OR tab_Messages.Msg_LastName IS NULL OR tab_Messages.Msg_LastFour IS NULL)" & " ORDER BY tab_Messages.Msg_Index;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Not sqlDataReader.HasRows Then
                        Response_WriteLine("<p>None to Parse!</p>")
                    Else
                        Response_WriteLine("<p>Found Records to Parse, beginning loop.  Doing cycles of " & blockSize & ".  Repeat this page until complete.<br>")
                        Response_WriteLine("#d6dbe9 colored parsed values indicate database was updated.<br>")
                        Response_WriteLine("- use ""&amp;begin=1"" to start at any index value<br>")
                        Response_WriteLine("- use ""&amp;really=Yes"" to write changes to the database</p>")
                        Response_WriteLine("<table>")
                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th>Index</th><th>Original FullID</th><th>Orig Last</th><th>Orig First</th><th>Orig Last4</th></tr>")
                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th>&nbsp;</th><th>&nbsp;</th><th>Parsed Last</th><th>Parsed First</th><th>Parsed Last4</th></tr>")
                        While sqlDataReader.Read = True
                            If cntr Mod 2 = 0 Then
                                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                            Else
                                Response_WriteLine("<tr>")
                            End If
                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Index") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_FullID") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_LastName") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_FirstName") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Msg_LastFour") & "</td>")
                            Response_WriteLine("</tr>")
                            If cntr Mod 2 = 0 Then
                                Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                            Else
                                Response_WriteLine("<tr>")
                            End If
                            Response_WriteLine("<td>&nbsp;</td>")
                            Response_WriteLine("<td>&nbsp;</td>")
                            Me.ParseFullID(sqlDataReader.Item("Msg_FullID"))
                            ' fills in gLAST, gFIRST, gSSN

                            If Me.GLAST <> "" And IsDBNull(sqlDataReader.Item("Msg_LastName")) Then
                                If really = "Yes" Then
                                    ' store
                                    UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_LastName = '" & Replace(Me.GLAST, "'", "''") & "' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">" & Me.GLAST & "</td>")
                                Else
                                    ' no store
                                    Response_WriteLine("<td>" & Me.GLAST & "</td>")
                                End If
                            Else
                                Response_WriteLine("<td>&nbsp;</td>")
                            End If

                            If Me.GFIRST <> "" And IsDBNull(sqlDataReader.Item("Msg_FirstName")) Then
                                If really = "Yes" Then
                                    ' store
                                    UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_FirstName = '" & Replace(Me.GFIRST, "'", "''") & "' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">" & Me.GFIRST & "</td>")
                                Else
                                    ' no store
                                    Response_WriteLine("<td>" & Me.GFIRST & "</td>")
                                End If
                            Else
                                Response_WriteLine("<td>&nbsp;</td>")
                            End If

                            If Me.GSSN <> "" And IsDBNull(sqlDataReader.Item("Msg_LastFour")) Then
                                If really = "Yes" Then
                                    ' store
                                    UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_LastFour = '" & Replace(Me.GSSN, "'", "''") & "' WHERE tab_Messages.Msg_Index = " & sqlDataReader.Item("Msg_Index") & ";")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">" & Me.GSSN & "</td>")
                                Else
                                    ' no store
                                    Response_WriteLine("<td>" & Me.GSSN & "</td>")
                                End If
                            Else
                                Response_WriteLine("<td>&nbsp;</td>")
                            End If
                            Response_WriteLine("</tr>")
                            Response_WriteLine("<tr bgcolor=""black""><td colspan=""5""></td></tr>")
                            cntr = cntr + 1
                            ' flush buffer every 100 rows
                            If cntr Mod 100 = 0 And Response.Buffer = True Then
                                'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.					
                                Response.Flush()
                                Response.Clear()
                            End If
                        End While
                        Response_WriteLine("</table>")
                        Response_WriteLine("<p>Done with loop of " & cntr & "</p>")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

            Case "Stranded"

                ' Find Stranded
                ' the purpose here would be to find OPEN Messages that are assigned to inactive or deleted Teams
                ' also OPEN Messages that are assigned to Active Teams that have inactive or deleted members

                Dim fail, str2, str3
                If (Not Request.QueryString("CheckType") Is Nothing) Then CheckType = Request.QueryString("CheckType").ToString() Else CheckType = ""

                ' Prevent this error:
                ' :Active Server Pages error 'ASP 0113' 
                ' :Script timed out 
                ' :The maximum amount of time for a script to execute was exceeded. You can change this limit by specifying a new value for the property Server.ScriptTimeout or by changing the value in the IIS administration tools.
                Server.ScriptTimeout = 600
                Response_WriteLine("<p>")
                Response_WriteLine("Check Stranded Messages missing: <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Team"">")
                If CheckType = "Team" Then
                    Response_WriteLine("<b>Team</b>")
                Else
                    Response_WriteLine("Team")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("-=-")
                Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Member"">")
                If CheckType = "Member" Then
                    Response_WriteLine("<b>Member</b>")
                Else
                    Response_WriteLine("Member")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("-=-")
                Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Audit"">")
                If CheckType = "Audit" Then
                    Response_WriteLine("<b>Audit</b>")
                Else
                    Response_WriteLine("Audit")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("</p>")
                Response_WriteLine("<p>")
                Response_WriteLine("<table>")
                Response_WriteLine("<tr><td>")
                Response_WriteLine("Team - display messages transferred to a Team that no longer exists.<br>")
                Response_WriteLine("Member - display messages assigned to a Member.<br>")
                Response_WriteLine("Audit - display audit records that could exist if messages were deleted without deleting the Audit record.<br>")
                Response_WriteLine("(Teams and Members that were incorrectly removed from the system could leave behind<br>")
                Response_WriteLine("a history of lost Messages that were associated to those Teams and Members)<br>")
                Response_WriteLine("</td></tr>")
                Response_WriteLine("</table>")
                Response_WriteLine("</p>")
                If CheckType = "Team" Then
                    Response_WriteLine("<p>")
                    Response_WriteLine("<table>")
                    Response_WriteLine("<tr><td><center><b>Stranded Messages</b></center></td></tr>")
                    Response_WriteLine("<tr><td>")
                    Response_WriteLine("This report searches for any Messages that are OPEN and no longer associated with active tab_Teams.")
                    Response_WriteLine("</td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    cntr = 0
                    sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Assigned, tab_Messages.Msg_LocationIndex," & " tab_Teams.Te_Index, tab_Teams.Te_Name, tab_Teams.Te_Active" & " FROM tab_Messages LEFT JOIN tab_Teams ON tab_Messages.Msg_TeamIndex = tab_Teams.Te_Index" & " WHERE tab_Messages.Msg_Completed IS NULL"
                    If Me.AdminSite = "000" Then
                        ' all sites
                    Else
                        If Me.AdminSite <> "" Then
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "'"
                        Else
                            'strange - so don't filter by site
                        End If
                    End If
                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Index DESC;"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString=" & sSqlString & "<br>")
                    End If

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            Response_WriteLine("<p>")
                            Response_WriteLine("<table>")
                            While sqlDataReader.Read = True
                                fail = "No"
                                If sqlDataReader.Item("Te_Active") = "No" Or IsDBNull(sqlDataReader.Item("Te_Active")) Then
                                    ' Team is inactive or missing
                                    fail = "Team"
                                End If
                                ' GetTeamMemberNames(i, ShowHidden, ShowEditLink)
                                ' ShowHidden: 
                                '   if true means return a list of all active members for the Team.
                                '   Nothing string if no active members
                                ' ShowEditLink: leave false for this list
                                If Me.GetTeamMemberNames(sqlDataReader.Item("Te_Index"), True, False) = "" Then
                                    fail = "Member"
                                End If
                                If fail <> "No" Then
                                    cntr = cntr + 1
                                    If cntr = 1 Then
                                        ' show header
                                        Response_WriteLine("<tr><th>Index</th><th>Assigned</th><th>Location</th><th>Team</th><th>T.Active</th><th>M.Active</th></tr>")
                                    End If
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & """>" & sqlDataReader.Item("Msg_Index") & "</a></td>")
                                    Response_WriteLine("<td>" & sqlDataReader.Item("Msg_Assigned") & "</td>")
                                    Response_WriteLine("<td>" & Me.GetLocationName(sqlDataReader.Item("Msg_LocationIndex")) & "</td>")
                                    If IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                        Response_WriteLine("<td><font color=""red"">Missing</font></td>")
                                    Else
                                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                            Response_WriteLine("<td>" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & "</td>")
                                        Else
                                            Response_WriteLine("<td>" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & "</td>")
                                        End If
                                    End If
                                    Response_WriteLine("<td>")
                                    If sqlDataReader.Item("Te_Active") <> "Yes" Then
                                        Response_WriteLine("<font color=""red"">No Active Team</font>")
                                    Else
                                        Response_WriteLine("Yes")
                                    End If
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    If fail = "Member" Then
                                        Response_WriteLine("<font color=""red"">No Members in Team</font>")
                                    Else
                                        Response_WriteLine("Yes")
                                    End If
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                End If
                            End While
                            If cntr = 0 Then
                                Response_WriteLine("<tr><td colspan=""6""><center><font color=""green"">GOOD: There are no Open Messages assigned to inactive or missing Teams.</font></center></td></tr>")
                            Else
                                If cntr = 1 Then
                                    Response_WriteLine("<tr><td colspan=""6""><center><font color=""red"">BAD: There is 1 Open Message assigned to inactive or missing Teams.</font></center></td></tr>")
                                Else
                                    Response_WriteLine("<tr><td colspan=""6""><center><font color=""red"">BAD: There are " & cntr & " Open Messages assigned to inactive or missing Teams.</font></center></td></tr>")
                                End If

                            End If
                            Response_WriteLine("</table></p>")
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                End If 'CheckType="Team"

                If CheckType = "Member" Then
                    ' Display a warning if Messages are assigned to a member username that doesn't exist in Teams table
                    Response_WriteLine("<p>")
                    Response_WriteLine("<table>")
                    Response_WriteLine("<tr><td><center><b>Stranded Messages</b></center></td></tr>")
                    Response_WriteLine("<tr><td>")
                    Response_WriteLine("This report searches for any Messages that are OPEN and assigned to a missing Member.")
                    Response_WriteLine("</td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</p>")
                    ' Results are very large so flush the buffer first to prevent reaching buffer size limits	
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        Response.Flush()
                        Response.Clear()
                    End If

                    prevUsername = ""
                    cntr2 = 0
                    str2 = ""

                    ' load recordset with all assigned Messages
                    sSqlString = "SELECT tab_Messages.Msg_Index, tab_Messages.Msg_Assigned, tab_Messages.Msg_TeamIndex, tab_Messages.Msg_Completed FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned IS NOT NULL AND tab_Messages.Msg_Completed IS NULL"
                    If Me.AdminSite = "000" Then
                        ' all sites
                    Else
                        If Me.AdminSite <> "" Then
                            sSqlString = sSqlString & " AND tab_Messages.Msg_SiteNum = '" & Me.AdminSite & "'"
                        Else
                            'strange - so don't filter by site
                        End If
                    End If
                    sSqlString = sSqlString & " ORDER BY tab_Messages.Msg_Assigned, tab_Messages.Msg_Index DESC;"
                    If _clsMessageVAR.BDebug = True Then
                        Response.Write("sSqlString=" & sSqlString & "<br>")
                    End If

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            Response_WriteLine("<p><font color=""navy"">BAD: There are no assigned Messages.  Get to work!</font></p>")
                        Else
                            While sqlDataReader.Read = True
                                If UCase(sqlDataReader.Item("Msg_Assigned")) = prevUsername Then
                                    ' skip
                                Else
                                    ' different.
                                    ' Update prevUsername and compare
                                    prevUsername = sqlDataReader.Item("Msg_Assigned")
                                    prevUsername = UCase(prevUsername)

                                    sSqlString = "SELECT tab_Members.Me_Index FROM tab_Members WHERE tab_Members.Me_Username LIKE '" & Replace(prevUsername, "'", "''") & "' AND tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Msg_TeamIndex") & ";"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                        If Not sqlDataReader2.HasRows Then
                                            ' BAD - no member found for tab_Messages.Msg_TeamIndex with matching tab_Messages.Msg_Username
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                str2 = str2 & "<tr><td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & """>" & sqlDataReader.Item("Msg_Index") & "</a></td><td>" & sqlDataReader.Item("Msg_Assigned") & "</td><td>" & Me.ColorizeTeamName(Me.GetTeamName(sqlDataReader.Item("Msg_TeamIndex"))) & "</td><td>" & sqlDataReader.Item("Msg_Completed") & "</td></tr>" & vbCrLf
                                            Else
                                                str2 = str2 & "<tr><td><a href=""" & _clsMessageVAR.WebAdminURL & "?A=Admin&S=" & S & "&I=" & sqlDataReader.Item("Msg_Index") & """>" & sqlDataReader.Item("Msg_Index") & "</a></td><td>" & sqlDataReader.Item("Msg_Assigned") & "</td><td>" & Me.ColorizeFont(Me.GetTeamName(sqlDataReader.Item("Msg_TeamIndex"))) & "</td><td>" & sqlDataReader.Item("Msg_Completed") & "</td></tr>" & vbCrLf
                                            End If
                                            cntr2 = cntr2 + 1
                                        Else
                                            ' GOOD - a member exists for tab_Messages.Msg_TeamIndex with matching tab_Messages.Msg_Username
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End If
                            End While

                            If cntr2 <> 0 Then
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table>")
                                Response_WriteLine("<tr><th>Index</th><th>Member</th><th>Team</th><th>Completed</th></tr>")
                                Response_WriteLine("" & str2 & "")
                                Response_WriteLine("</table>")
                                If cntr2 = 1 Then
                                    Response_WriteLine("<font color=""red"">BAD: There is 1 Open Message assigned to non-existent Member Usernames.</font><br>")
                                Else
                                    Response_WriteLine("<font color=""red"">BAD: There are " & cntr2 & " Open Messages assigned to non-existent Member Usernames.</font><br>")
                                End If
                                Response_WriteLine("</p>")
                            Else
                                Response_WriteLine("<p><font color=""green"">GOOD: There are no Open Messages assigned to non-existent Member Usernames.</font></p>")
                            End If
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                End If 'CheckType = "Member"

                If CheckType = "Team" Or CheckType = "Member" Then
                    Response_WriteLine("<p>")
                    If cntr + cntr2 > 0 Then
                        Response_WriteLine("<font color=""red"">Database Dirty.</font>  Click each Index to act on them.  There")
                        If cntr + cntr2 = 1 Then
                            Response_WriteLine("is 1 Message")
                        Else
                            Response_WriteLine("are " & cntr + cntr2 & " Messages")
                        End If
                        Response_WriteLine("with missing Teams/Members")
                    End If
                    If Me.AdminSite = "000" Then
                        ' all sites
                        Response_WriteLine("Checked All Sites.")
                    Else
                        If Me.AdminSite <> "" Then
                            Response_WriteLine("Checked only " & Me.SiteName & ".")
                        Else
                            Response_WriteLine("Checked All Sites.")
                        End If
                    End If
                    Response_WriteLine("</p>")
                End If


                If CheckType = "Audit" Then
                    ' find unmatched Audit entries
                    ' they would exist if messages were deleted without deleting an Audit record
                    Response_WriteLine("<p>")
                    Response_WriteLine("<table>")
                    Response_WriteLine("<tr><td><center><b>Stranded Audits</b></center></td></tr>")
                    Response_WriteLine("<tr><td>")
                    Response_WriteLine("This report searches for any Audit records that point to a Message that doesn't exist.")
                    Response_WriteLine("</td></tr>")
                    Response_WriteLine("</table>")
                    Response_WriteLine("</p>")
                    ' Results are very large so flush the buffer first to prevent reaching buffer size limits	
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        Response.Flush()
                        Response.Clear()
                    End If

                    sSqlString = "SELECT DISTINCT(tab_Audit.Au_IndexMessage) AS DISINDEX" & " FROM tab_Audit LEFT JOIN tab_Messages ON tab_Audit.Au_IndexMessage = tab_Messages.Msg_Index" & " WHERE tab_Messages.Msg_Index Is Null;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If Not sqlDataReader.HasRows Then
                            str3 = str3 & "<p><font color=""green"">GOOD: are 0 Audit records without a corresponding Message.</font></p>"
                        Else
                            str3 = str3 & "<p>Found Audit records w/o matching Messages. Run the"
                            str3 = str3 & " <a href=""" & _clsMessageVAR.WebAdminURL & "A=Setup&S=" & S & "&menu=Purge"">Purge</a> menu item to fix stranded audits records<br>Index: "
                            While sqlDataReader.Read = True
                                str3 = str3 & sqlDataReader.Item("DISINDEX") & ", "
                            End While
                            str3 = str3 & "</p>"
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try
                    Response.Write(str3)
                    str3 = ""
                End If 'CheckType = "Audit"

            Case "StrandedUsers"
                ' poll AD to see if accounts exist 
                ' Will show people that have left the VA that way
                '   loop through 
                '	  unique tab_Members WHERE ACTIVE=’Yes’  (there can be duplicate usernames)
                '	  Admins  (already no duplictes)

                prevUsername = ""
                cntr = 0
                cntr2 = 0
                If (Not Request.QueryString("CheckType") Is Nothing) Then CheckType = Request.QueryString("CheckType").ToString() Else CheckType = ""

                ' Prevent this error:
                ' :Active Server Pages error 'ASP 0113' 
                ' :Script timed out 
                ' :The maximum amount of time for a script to execute was exceeded. You can change this limit by specifying a new value for the property Server.ScriptTimeout or by changing the value in the IIS administration tools.
                Server.ScriptTimeout = 600
                Response_WriteLine("<p>")
                Response_WriteLine("Check Stranded: <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Members"">")
                If CheckType = "Members" Then
                    Response_WriteLine("<b>Members</b>")
                Else
                    Response_WriteLine("Members")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("-=-")
                Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Admins"">")
                If CheckType = "Admins" Then
                    Response_WriteLine("<b>Admins</b>")
                Else
                    Response_WriteLine("Admins")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("</p>")
                Response_WriteLine("<p>")
                Response_WriteLine("<table>")
                Response_WriteLine("<tr><td>")
                Response_WriteLine("Members - inactivates Team Members that no longer exist in the Active Directory Domain.<br>")
                Response_WriteLine("Admins - deletes Administrators that no longer exist in the Active Directory Domain.")
                Response_WriteLine("</td></tr>")
                Response_WriteLine("</table>")
                Response_WriteLine("</p>")
                If CheckType = "Members" Then
                    Response_WriteLine("<p><b>Stranded Users</b></p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    sSqlString = "SELECT tab_Members.Me_Username, tab_Members.Me_Index, tab_Members.Me_TeamIndex, tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members WHERE tab_Members.Me_Active = 'Yes' ORDER BY tab_Members.Me_Username;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            Response_WriteLine("<p><table><tr bgcolor=""#eeeeee""><th colspan=""5"">Team Members</th></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><th>Username</th><th>Name</th><th>Title</th><th>Team</th><th>Inactivated</th></tr>")
                            While sqlDataReader.Read = True
                                If UCase(prevUsername) = UCase(sqlDataReader.Item("Me_Username")) Then
                                    ' don't check AD
                                Else
                                    ' check AD if username exists
                                    If Not Me.ValidateADUser(sqlDataReader.Item("Me_Username")) Then
                                        cntr = cntr + 1
                                        Response_WriteLine("<tr>")
                                        Response_WriteLine("<td><font color=""red"">" & sqlDataReader.Item("Me_Username") & "</font></td>")
                                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Name") & "</td>")
                                        Response_WriteLine("<td>" & sqlDataReader.Item("Me_Title") & "</td>")
                                        Response_WriteLine("<td><small>" & Me.GetTeamListFromUsername(sqlDataReader.Item("Me_Username")) & "</small></td>")
                                        sSqlString = "UPDATE tab_Members SET tab_Members.Me_Active = 'No' WHERE tab_Members.Me_Username LIKE '" & sqlDataReader.Item("Me_Username") & "';"
                                        UpdateTableRecords(sSqlString)
                                        errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                        If errstore <> "Success" Then
                                            Response_WriteLine("<td><font color=""red"">" & errstore & "</font></td>")
                                        Else
                                            Response_WriteLine("<td><font color=""green"">" & errstore & "</font></td>")
                                        End If
                                        Response_WriteLine("</tr>")
                                    End If
                                End If

                                prevUsername = sqlDataReader.Item("Me_Username")
                            End While
                            If cntr = 0 Then
                                Response_WriteLine("<tr><td colspan=""5""><center><font color=""green"">Good: no invalid Team Member Usernames are in the system.</font></center></td></tr>")
                            Else
                                Response_WriteLine("<tr><td colspan=""5""><center><font color=""red"">Bad: there were invalid Team Member Usernames in the system that were changed to Inactive. Check View Audit for details.</font></center></td></tr>")
                            End If
                            Response_WriteLine("</table></p>")
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                End If 'CheckType = "Members"

                If CheckType = "Admins" Then
                    Response_WriteLine("<p><b>Stranded Admins</b></p>")
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        'if anything you do needs to  Response.Headers, you can't do it after any part of the Response has been Flushed.
                        Response.Flush()
                    End If

                    prevUsername = ""
                    sSqlString = "SELECT tab_Admins.Adm_Username, tab_Admins.Adm_Name, tab_Admins.Adm_SiteNum, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Notes FROM tab_Admins ORDER BY tab_Admins.Adm_SiteNum, tab_Admins.Adm_Username;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            Response_WriteLine("<p><table><tr bgcolor=""#eeeeee""><th colspan=""4"">Admins</th></tr>")
                            Response_WriteLine("<tr bgcolor=""#eeeeee""><th>Username</th><th>Name</th><th>More Info</th><th>Deleted</th>")
                            While sqlDataReader.Read = True
                                If UCase(prevUsername) = UCase(sqlDataReader.Item("Adm_Username")) Then
                                    ' don't check AD
                                Else
                                    ' check AD if username exists
                                    If Not Me.ValidateADUser(sqlDataReader.Item("Adm_Username")) Then
                                        cntr2 = cntr2 + 1
                                        Response_WriteLine("<tr><td><font color=""red"">" & sqlDataReader.Item("Adm_Username") & "</font></td>")
                                        Response_WriteLine("<td>" & sqlDataReader.Item("Adm_Name") & "</td>")
                                        Response_WriteLine("<td><small>(" & sqlDataReader.Item("Adm_SiteNum") & "&nbsp;" & sqlDataReader.Item("Adm_AccessLevel") & ")&nbsp;" & sqlDataReader.Item("Adm_Notes") & "</small></td>")
                                        sSqlString = "DELETE FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & sqlDataReader.Item("Adm_Username") & "';"
                                        DeleteTableRecords(sSqlString)
                                        errstore = Me.StoreAuditAdmin("Remove Admin", sSqlString)
                                        If errstore <> "Success" Then
                                            Response_WriteLine("<td><font color=""red"">" & errstore & "</font></td>")
                                        Else
                                            Response_WriteLine("<td><font color=""green"">" & errstore & "</font></td>")
                                        End If
                                        Response_WriteLine("</tr>")
                                    End If
                                End If

                                prevUsername = sqlDataReader.Item("Adm_Username")
                            End While
                            If cntr2 = 0 Then
                                Response_WriteLine("<tr><td colspan=""4""><center><font color=""green"">Good: no invalid Admin Usernames are in the system</font></center></td></tr>")
                            Else
                                Response_WriteLine("<tr><td colspan=""4""><center><font color=""red"">Bad: there were invalid Admin Usernames in the system that were deleted. Check View Audit for details.</font></center></td></tr>")
                            End If
                            Response_WriteLine("</table></p>")
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                End If 'CheckType = "Admins"
                Response_WriteLine("<p>")
                If CheckType <> "" And cntr + cntr2 > 0 Then
                    Response_WriteLine("<font color=""red"">Database was Dirty.</font> There")
                    If cntr + cntr2 = 1 Then
                        Response_WriteLine("was 1")
                    Else
                        Response_WriteLine("were " & cntr + cntr2 & "")
                    End If
                    Response_WriteLine("Active invalid Usernames in the system.")
                End If
                Response_WriteLine("</p>")
            Case "Check"
                '
                ' CHECK CONSISTENCY
                '
                ' Database Check for consistency things:
                If (Not Request.QueryString("CheckType") Is Nothing) Then
                    CheckType = Request.QueryString("CheckType").ToString()
                Else
                    CheckType = ""
                End If

                ' Prevent this error:
                ' :Active Server Pages error 'ASP 0113' 
                ' :Script timed out 
                ' :The maximum amount of time for a script to execute was exceeded. You can change this limit by specifying a new value for the property Server.ScriptTimeout or by changing the value in the IIS administration tools.
                Server.ScriptTimeout = 600
                Response_WriteLine("<p>Check Consistency on this:")
                Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Admins"">")
                If CheckType = "Admins" Then
                    Response_WriteLine("<b>Admins</b>")
                Else
                    Response_WriteLine("Admins")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Members"">")
                If CheckType = "Members" Then
                    Response_WriteLine("<b>Members</b>")
                Else
                    Response_WriteLine("Members")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Flags"">")
                If CheckType = "Flags" Then
                    Response_WriteLine("<b>Escalation Recipients</b>")
                Else
                    Response_WriteLine("Escalation Recipients")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Sort"">")
                If CheckType = "Sort" Then
                    Response_WriteLine("<b>Sort Ordering</b>")
                Else
                    Response_WriteLine("Sort Ordering")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships"">")
                If CheckType = "Relationships" Then
                    Response_WriteLine("<b>Structural Relationships</b>")
                Else
                    Response_WriteLine("Structural Relationships")
                End If
                Response_WriteLine("</a>")
                Response_WriteLine("</p>")
                ' this menu header if statement is repeated at the end of the "Check" Case statement to close out the tables and paragraph
                If CheckType = "Admins" Or CheckType = "Members" Or CheckType = "Flags" Or CheckType = "Sort" Or CheckType = "Relationships" Then
                    Response_WriteLine("<p>Checking " & CheckType & " for incomplete settings</p>")
                Else
                    Response_WriteLine("<p><table><tr><td>")
                    Response_WriteLine("Admins - display a warning about members being in the admins table. (generally not necessary so delete the Admin)<br>")
                    Response_WriteLine("Members - display a warning about members being listed multiple times for the same Team.<br>")
                    Response_WriteLine("Escalation Recipients - Display a warning if a Site has no Escalation email recipients.<br>")
                    Response_WriteLine("Sort Ordering - Check the members, teams, locations and sites to ensure sort ordering integrety is correct.<br>")
                    Response_WriteLine("Structural Relationships - Check for members, teams, locations that may have been disconnected from the tree.")
                    Response_WriteLine("</td></tr></table></p>")
                End If

                ' Results are very large so flush the buffer first to prevent reaching buffer size limits	
                If Response.Buffer = True Then
                    'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                    Response.Flush()
                    Response.Clear()
                End If

                If CheckType = "Admins" Then
                    ' display a warning about members being in the admins table.
                    ' check for tab_Members.Me_Username = tab_Admins.Adm_Username
                    cntr = 0
                    sSqlString = "SELECT tab_Admins.Adm_Username, tab_Members.Me_Username, tab_Members.Me_Active, tab_Admins.Adm_SiteNum, tab_Admins.Adm_AccessLevel" & " FROM tab_Members INNER JOIN tab_Admins ON tab_Members.Me_Username LIKE tab_Admins.Adm_Username;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            While sqlDataReader.Read = True
                                cntr = cntr + 1
                                If sqlDataReader.Item("Me_Active") = "Yes" Then
                                    ' HEAVY WARNING
                                    Response_WriteLine("<font color=""red"">WARNING: Active Member " & Me.CleanUserName(sqlDataReader.Item("Me_Username")) & " is in Admins table with " & sqlDataReader.Item("Adm_AccessLevel") & " access for " & sqlDataReader.Item("Adm_SiteNum") & ".</font><br>")
                                Else
                                    ' LIGHT WARNING
                                    Response_WriteLine("<font color=""orange"">CAUTION: In-Active Member " & Me.CleanUserName(sqlDataReader.Item("Me_Username")) & " is in Admins table with " & sqlDataReader.Item("Adm_AccessLevel") & " access for " & sqlDataReader.Item("Adm_SiteNum") & ".</font><br>")
                                End If
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If cntr = 0 Then
                        ' GOOD
                        Response_WriteLine("<font color=""green"">GOOD: No Members are also Admins</font>")
                    End If
                End If 'Admins

                If CheckType = "Members" Then
                    ' display a warning about members being listed multiple times for the same Team
                    ' check for tab_Members.Me_TeamIndex = tab_Members.Me_TeamIndex && tab_Members.Me_Username = tab_Members.Me_Username	

                    Dim MemberIndex, MemberCount, MemberMax, MemberString
                    cntr = 0
                    MemberMax = 0
                    MemberString = "Choose an Index Range: "
                    MemberCount = 0

                    ' This section displays the header in the format of:
                    ' 1 to 500 -=- 501 to 1000 -=- 1001 to 1500 -=- 1501 to 2000 -=- 2001 to 2500 -=- 2501 to 3000 -=- 3001 to 3138
                    sSqlString = "SELECT MAX(tab_Members.Me_Index) AS THEMAX FROM tab_Members;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.Read = False Then
                            MemberMax = 0
                        Else
                            If IsDBNull(sqlDataReader.Item("THEMAX")) Then
                                MemberMax = 0
                            Else
                                MemberMax = sqlDataReader.Item("THEMAX")
                            End If
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If MemberMax <= 500 Then
                        ' Display single "1 to x" when total is less than 500
                        MemberString = MemberString & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Members&MemberIndex=0"">1 to " & MemberMax & "</a>"
                    Else
                        ' display "1 to" primer
                        MemberString = MemberString & "<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Members&MemberIndex=0"">1 to 500</a>" & vbCrLf
                        MemberCount = MemberCount + 500

                        ' loop to the highest displaying "to xxx" in batches of 500
                        Do While MemberCount <= MemberMax - 500
                            MemberString = MemberString & " -=- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Members&MemberIndex=" & MemberCount & """>" & MemberCount + 1 & " to " & MemberCount + 500 & "</a>" & vbCrLf
                            MemberCount = MemberCount + 500
                        Loop

                        ' display wrapper for the remainder
                        MemberString = MemberString & " -=- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Members&MemberIndex=" & MemberCount & """>" & MemberCount + 1 & " to " & MemberMax & "</a>"
                    End If
                    Response.Write(MemberString)

                    ' Creates sSqlString statement from pre-chosen MemberIndex 500 pool range.  If not pre-chosen, starts at 1.
                    If (Not Request.QueryString("MemberIndex") Is Nothing) Then MemberIndex = Request.QueryString("MemberIndex").ToString() Else MemberIndex = ""
                    If MemberIndex = "" Then MemberIndex = 0
                    If Not IsNumeric(MemberIndex) Then
                        ' error cannot display
                        Response_WriteLine("<p>Choose a range to search the Member Indexes</p>")
                    Else
                        MemberIndex = CInt(MemberIndex)
                        sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_Username, tab_Members.Me_TeamIndex FROM tab_Members"
                        sSqlString = sSqlString & " WHERE tab_Members.Me_Index > " & MemberIndex & " AND tab_Members.Me_Index <= " & MemberIndex + 500
                        sSqlString = sSqlString & " ORDER BY tab_Members.Me_Index;"
                        If MemberMax <= 500 Then
                            Response.Write("<p>Showing Index 1 to " & MemberMax & "</p>")
                        Else
                            If MemberIndex + 500 > MemberMax Then
                                Response.Write("<p>Showing Index " & MemberIndex + 1 & " to " & MemberMax & "</p>")
                            Else
                                Response.Write("<p>Showing Index " & MemberIndex + 1 & " to " & MemberIndex + 500 & "</p>")
                            End If
                        End If

                        ' Show the Consistency Check on the Members

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    sSqlString = "SELECT tab_Members.Me_Username, tab_Members.Me_TeamIndex FROM tab_Members" & " WHERE tab_Members.Me_Username LIKE '" & sqlDataReader.Item("Me_Username") & "' AND tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Me_TeamIndex") & " AND NOT tab_Members.Me_Index = " & sqlDataReader.Item("Me_Index") & " ORDER BY tab_Members.Me_TeamIndex, tab_Members.Me_SortOrder;"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                        If sqlDataReader2.HasRows = True Then
                                            While sqlDataReader2.Read = True
                                                cntr = cntr + 1
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine("<font color=""red"">WARNING: Member " & sqlDataReader.Item("Me_Username") & " is listed multiple times for " & Me.ColorizeTeamName(Me.GetTeamName(sqlDataReader.Item("Me_TeamIndex"))) & ".</font><br>")
                                                Else
                                                    Response_WriteLine("<font color=""red"">WARNING: Member " & sqlDataReader.Item("Me_Username") & " is listed multiple times for " & Me.ColorizeFont(Me.GetTeamName(sqlDataReader.Item("Me_TeamIndex"))) & ".</font><br>")
                                                End If
                                                If cntr Mod 500 = 0 Then
                                                    ' every 500 entries flush the buffer
                                                    If Response.Buffer = True Then
                                                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                                                        Response.Flush()
                                                        Response.Clear()
                                                    End If
                                                End If
                                            End While
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        If cntr = 0 Then
                            Response_WriteLine("<font color=""green"">GOOD: All Members are only listed once per Team.</font><br>")
                        End If
                    End If 'IsNumeric(MemberIndex)
                End If 'Members

                If CheckType = "Flags" Then
                    ' Display a warning if a Site has no Escalation email recipients
                    ' send to:
                    ' AdminSite = 000 or nnn
                    ' AND AdminType = "All" or matches
                    ' AND Adm_Email IS NOT NULL
                    Dim oldSN, oldType
                    oldSN = ""
                    oldType = ""
                    If Me.AdminSite = "000" Then
                        ' show all Sites
                        sSqlString = "SELECT tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Type FROM tab_Locations WHERE tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_Type, tab_Locations.Lo_SortOrder;"
                    Else
                        ' show only this Site
                        sSqlString = "SELECT tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Type FROM tab_Locations WHERE tab_Locations.Lo_Active = 'Yes' AND tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_Type, tab_Locations.Lo_SortOrder;"
                    End If

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            While sqlDataReader.Read = True
                                If sqlDataReader.Item("Lo_SiteNum") = oldSN And sqlDataReader.Item("Lo_Type") = oldType Then
                                    ' same Site/Type, don't re-check
                                Else
                                    ' make the old variables actually the new values
                                    oldSN = sqlDataReader.Item("Lo_SiteNum")
                                    oldType = sqlDataReader.Item("Lo_Type")

                                    ' new Site/Type, recheck
                                    sSqlString = "SELECT COUNT(Adm_Username) AS THECOUNT FROM tab_Admins" & " WHERE tab_Admins.Adm_EMAIL IS NOT NULL" & " AND (tab_Admins.Adm_Type = '" & oldType & "' OR tab_Admins.Adm_Type = 'All')" & " AND (tab_Admins.Adm_AccessLevel = 'Admin' OR tab_Admins.Adm_AccessLevel = 'Site')" & " AND (tab_Admins.Adm_SiteNum = '" & oldSN & "' OR tab_Admins.Adm_SiteNum = '000');"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader
                                        sqlDataReader2.Read()
                                        thecount = sqlDataReader2.Item("THECOUNT")

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    If thecount = 0 Then
                                        ' BAD...
                                        Response_WriteLine("<font color=""red"">WARNING: " & sqlDataReader.Item("Lo_SiteNum") & " type " & sqlDataReader.Item("Lo_Type") & " has 0 recipients defined for flagged message escalation.</font><br>")
                                    Else
                                        ' Good...
                                        If thecount = 1 Then
                                            Response_WriteLine("<font color=""green"">GOOD: " & sqlDataReader.Item("Lo_SiteNum") & " type " & sqlDataReader.Item("Lo_Type") & " has 1 recipient defined for flagged message escalation.</font><br>")
                                        Else
                                            Response_WriteLine("<font color=""green"">GOOD: " & sqlDataReader.Item("Lo_SiteNum") & " type " & sqlDataReader.Item("Lo_Type") & " has " & thecount & " recipients defined for flagged message escalation.</font><br>")
                                        End If
                                    End If
                                End If
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                End If 'Flags

                If CheckType = "Sort" Then
                    ' Sort goofups
                    Dim oldIndex, oldTeamIndex, oldLocationIndex, oldSiteNum

                    ' Display a warning if multiple Members in same team have same sortorder
                    oldSortOrder = -1
                    oldIndex = -1
                    oldTeamIndex = -1
                    oldName = "Nothing"
                    oldActive = "Nothing"
                    cntr = 0
                    sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder, tab_Members.Me_TeamIndex, tab_Members.Me_Active, tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members ORDER BY tab_Members.Me_TeamIndex, tab_Members.Me_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            While sqlDataReader.Read = True
                                If sqlDataReader.Item("Me_TeamIndex") = oldTeamIndex Then
                                    If sqlDataReader.Item("Me_SortOrder") = oldSortOrder Then
                                        ' same sort order as last time  i.e. 10 = 10
                                        cntr = cntr + 1
                                        Response_WriteLine("<font color=""red"">WARNING: Member ")
                                        Response_WriteLine("" & sqlDataReader.Item("Me_Index") & ":" & sqlDataReader.Item("Me_Active") & ":" & sqlDataReader.Item("Me_Name") & "")
                                        If Not IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                            Response_WriteLine("&nbsp;" & sqlDataReader.Item("Me_Title") & "")
                                        End If
                                        Response_WriteLine("has same SortOrder " & sqlDataReader.Item("Me_SortOrder") & " as another member")
                                        Response_WriteLine("" & oldIndex & ":" & oldActive & ":" & oldName & " of Team ")
                                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                            Response_WriteLine("" & sqlDataReader.Item("Me_TeamIndex") & ":" & Me.ColorizeTeamName(Me.GetTeamName(sqlDataReader.Item("Me_TeamIndex"))) & ".</font><br>")
                                        Else
                                            Response_WriteLine("" & sqlDataReader.Item("Me_TeamIndex") & ":" & Me.ColorizeFont(Me.GetTeamName(sqlDataReader.Item("Me_TeamIndex"))) & ".</font><br>")
                                        End If
                                    Else
                                        ' good, new sort order in same Team
                                    End If
                                Else
                                    ' new team
                                End If
                                oldSortOrder = sqlDataReader.Item("Me_SortOrder")
                                oldTeamIndex = sqlDataReader.Item("Me_TeamIndex")
                                oldIndex = sqlDataReader.Item("Me_Index")
                                oldName = sqlDataReader.Item("Me_Name")
                                oldActive = sqlDataReader.Item("Me_Active")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If cntr = 0 Then
                        Response_WriteLine("<font color=""green"">GOOD: No Team's Members share same SortOrder.</font><br>")
                    End If

                    ' Display a warning if multiple Teams in same Location have same sortorder
                    oldSortOrder = -1
                    oldTeamIndex = -1
                    oldLocationIndex = -1
                    oldName = "Nothing"
                    oldActive = "Nothing"
                    cntr = 0
                    sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_Active, tab_Teams.Te_SortOrder, tab_Teams.Te_LocationIndex, tab_Teams.Te_Name FROM tab_Teams ORDER BY tab_Teams.Te_LocationIndex, tab_Teams.Te_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            While sqlDataReader.Read = True
                                If sqlDataReader.Item("Te_LocationIndex") = oldLocationIndex Then
                                    If sqlDataReader.Item("Te_SortOrder") = oldSortOrder Then
                                        ' same sort order as last time  i.e. 10 = 10
                                        cntr = cntr + 1
                                        Response_WriteLine("<font color=""red"">WARNING: Team ")
                                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                            Response_WriteLine("" & sqlDataReader.Item("Te_Index") & ":" & sqlDataReader.Item("Te_Active") & ":" & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & " ")
                                        Else
                                            Response_WriteLine("" & sqlDataReader.Item("Te_Index") & ":" & sqlDataReader.Item("Te_Active") & ":" & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & " ")
                                        End If
                                        Response_WriteLine("has same SortOrder " & sqlDataReader.Item("Te_SortOrder") & " as another Team ")
                                        Response_WriteLine("" & oldTeamIndex & ":" & oldActive & ":" & oldName & " of Location ")
                                        Response_WriteLine("" & sqlDataReader.Item("Te_LocationIndex") & ":" & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & ".</font><br>")
                                    Else
                                        ' good, new sort order in same location
                                    End If
                                Else
                                    ' new location
                                End If
                                oldSortOrder = sqlDataReader.Item("Te_SortOrder")
                                oldTeamIndex = sqlDataReader.Item("Te_Index")
                                oldLocationIndex = sqlDataReader.Item("Te_LocationIndex")
                                oldName = sqlDataReader.Item("Te_Name")
                                oldActive = sqlDataReader.Item("Te_Active")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If cntr = 0 Then
                        Response_WriteLine("<font color=""green"">GOOD: No Location's Teams share same SortOrder.</font><br>")
                    End If

                    ' Display a warning if multiple Locations in Site have same sortorder
                    oldSortOrder = -1
                    oldLocationIndex = -1
                    oldSiteNum = "NONE"
                    oldName = "Nothing"
                    oldActive = "Nothing"
                    cntr = 0
                    sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            While sqlDataReader.Read = True
                                If sqlDataReader.Item("Lo_SiteNum") = oldSiteNum Then
                                    If sqlDataReader.Item("Lo_SortOrder") = oldSortOrder Then
                                        ' same sort order as last time  i.e. 10 = 10
                                        cntr = cntr + 1
                                        Response_WriteLine("<font color=""red"">WARNING: Location ")
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_Index") & ":" & sqlDataReader.Item("Lo_Active") & ":" & sqlDataReader.Item("Lo_Name") & " ")
                                        Response_WriteLine("has same SortOrder " & sqlDataReader.Item("Lo_SortOrder") & " as another Location ")
                                        Response_WriteLine("" & oldLocationIndex & ":" & oldActive & ":" & oldName & " of Site ")
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & ".</font><br>")
                                    End If
                                End If
                                oldSortOrder = sqlDataReader.Item("Lo_SortOrder")
                                oldLocationIndex = sqlDataReader.Item("Lo_Index")
                                oldSiteNum = sqlDataReader.Item("Lo_SiteNum")
                                oldName = sqlDataReader.Item("Lo_Name")
                                oldActive = sqlDataReader.Item("Lo_Active")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If cntr = 0 Then
                        Response_WriteLine("<font color=""green"">GOOD: No Site's Locations share same SortOrder.</font><br>")
                    End If

                    ' Display a warning if multiple Sites have same sortorder
                    oldSortOrder = -1
                    oldSiteNum = "NONE"
                    oldName = "Nothing"
                    oldActive = "Nothing"
                    cntr = 0
                    sSqlString = "SELECT tab_Sites.Si_SiteOrder, tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites ORDER BY tab_Sites.Si_SiteOrder, tab_Sites.Si_SiteNum;"

                    MyCommand.CommandText = sSqlString

                    Try
                        If MyConnection.State = ConnectionState.Closed Then
                            MyConnection.Open()
                        End If

                        sqlDataReader = MyCommand.ExecuteReader

                        If sqlDataReader.HasRows = True Then
                            While sqlDataReader.Read = True
                                If sqlDataReader.Item("Si_SiteOrder") = oldSortOrder Then
                                    ' same sort order as last time  i.e. 10 = 10
                                    cntr = cntr + 1
                                    Response_WriteLine("<font color=""red"">WARNING: Site ")
                                    Response_WriteLine("" & sqlDataReader.Item("Si_SiteNum") & ":" & sqlDataReader.Item("Si_Name") & " ")
                                    Response_WriteLine("has same SortOrder " & sqlDataReader.Item("Si_SiteOrder") & " as another Site ")
                                    Response_WriteLine("" & oldSiteNum & ":" & oldName & ":" & oldActive & ".</font><br>")
                                End If
                                oldSortOrder = sqlDataReader.Item("Si_SiteOrder")
                                oldSiteNum = sqlDataReader.Item("Si_SiteNum")
                                oldName = sqlDataReader.Item("Si_Name")
                                oldActive = sqlDataReader.Item("Si_Active")
                            End While
                        End If

                    Catch ex As Exception
                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                    Finally
                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                    End Try

                    If cntr = 0 Then
                        Response_WriteLine("<font color=""green"">GOOD: No Sites share same SortOrder.</font><br>")
                    End If
                End If 'Sort

                If CheckType = "Relationships" Then

                    Dim SubType
                    If (Not Request.QueryString("SubType") Is Nothing) Then SubType = Request.QueryString("SubType").ToString() Else SubType = ""
                    Response_WriteLine("<p>Check Relationships on:")
                    Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships&SubType=SiteNoLoc"">")
                    If SubType = "SiteNoLoc" Then
                        Response_WriteLine("<b>SiteNoLoc</b>")
                    Else
                        Response_WriteLine("SiteNoLoc")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships&SubType=LocNoSite"">")
                    If SubType = "LocNoSite" Then
                        Response_WriteLine("<b>LocNoSite</b>")
                    Else
                        Response_WriteLine("LocNoSite")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships&SubType=LocNoTeam"">")
                    If SubType = "LocNoTeam" Then
                        Response_WriteLine("<b>LocNoTeam</b>")
                    Else
                        Response_WriteLine("LocNoTeam")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships&SubType=TeamNoLoc"">")
                    If SubType = "TeamNoLoc" Then
                        Response_WriteLine("<b>TeamNoLoc</b>")
                    Else
                        Response_WriteLine("TeamNoLoc")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships&SubType=TeamNoMem"">")
                    If SubType = "TeamNoMem" Then
                        Response_WriteLine("<b>TeamNoMem</b>")
                    Else
                        Response_WriteLine("TeamNoMem")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&CheckType=Relationships&SubType=MemNoTeam"">")
                    If SubType = "MemNoTeam" Then
                        Response_WriteLine("<b>MemNoTeam</b>")
                    Else
                        Response_WriteLine("MemNoTeam")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("</p>")
                    ' this menu header if statement is repeated at the end of the "Check" Case statement to close out the tables and paragraph
                    If SubType = "SiteNoLoc" Or SubType = "LocNoSite" Or SubType = "LocNoTeam" Or SubType = "TeamNoLoc" Or SubType = "TeamNoMem" Or SubType = "MemNoTeam" Then
                        Response_WriteLine("<p>Checking " & SubType & " for incomplete settings</p>")
                    Else
                        Response_WriteLine("<p><table><tr><td>")
                        Response_WriteLine("SiteNoLoc - Display a warning if a Site (w/ active=Yes) has no Locations (w/ active=Yes).<br>")
                        Response_WriteLine("LocNoSite - Display a warning if a Location (w/ active=Yes) has no Sites (w/ active=Yes).<br>")
                        Response_WriteLine("LocNoTeam - Display a warning if a Location (w/ active=Yes) has no Teams (w/ active=Yes).<br>")
                        Response_WriteLine("TeamNoLoc - Display a warning if a Team (w/ active=Yes) has no Locations (w/ active=Yes).<br>")
                        Response_WriteLine("TeamNoMem - Display a warning if a Team (w/ active=Yes) has no members (w/ active=Yes).<br>")
                        Response_WriteLine("MemNoTeam - Display a warning if a Member (w/ active=Yes) has no Teams (w/ active=Yes).				")
                        Response_WriteLine("</td></tr></table></p>")
                    End If

                    ' Results are very large so flush the buffer first to prevent reaching buffer size limits	
                    If Response.Buffer = True Then
                        'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                        Response.Flush()
                        Response.Clear()
                    End If

                    If SubType = "SiteNoLoc" Then
                        ' Display a warning if a Site (w/ active=Yes) has no Locations (w/ active=Yes)
                        cntr = 0
                        If Me.AdminSite = "000" Then
                            ' show all Sites
                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_Active = 'Yes' AND tab_Sites.Si_SiteNum <> '000' ORDER BY tab_Sites.Si_SiteOrder;"
                        Else
                            ' show only this Site
                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_Active = 'Yes' AND tab_Sites.Si_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Sites.Si_SiteOrder;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    cntr = cntr + 1
                                    sSqlString = "SELECT COUNT(tab_Locations.Lo_Index) AS THECOUNT FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & sqlDataReader.Item("Si_SiteNum") & "' AND tab_Locations.Lo_Active = 'Yes';"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader
                                        sqlDataReader2.Read()
                                        If sqlDataReader2.Item("THECOUNT") = 0 Then
                                            ' BAD...
                                            Response_WriteLine("<font color=""red"">WARNING: Site " & sqlDataReader.Item("Si_Name") & " has 0 Locations.</font><br>")
                                        Else
                                            ' Good...
                                            If sqlDataReader2.Item("THECOUNT") = 1 Then
                                                Response_WriteLine("<font color=""green"">GOOD: Site " & sqlDataReader.Item("Si_Name") & " has 1 Location.</font><br>")
                                            Else
                                                Response_WriteLine("<font color=""green"">GOOD: Site " & sqlDataReader.Item("Si_Name") & " has " & sqlDataReader2.Item("THECOUNT") & " Locations.</font><br>")
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        If cntr = 0 Then
                            Response_WriteLine("<font color=""red"">WARNING: There are no Active Sites.</font><br>")
                        End If
                    End If 'SubType

                    If SubType = "LocNoSite" Then
                        ' Display a warning if a Location (w/ active=Yes) has no Sites (w/ active=Yes)
                        cntr = 0
                        If Me.AdminSite = "000" Then
                            ' show all Sites
                            sSqlString = "SELECT tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
                        Else
                            ' show only this Site
                            sSqlString = "SELECT tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name FROM tab_Locations" & " WHERE tab_Locations.Lo_Active = 'Yes' AND tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    cntr = cntr + 1
                                    sSqlString = "SELECT tab_Sites.Si_Name FROM tab_Sites WHERE tab_Sites.Si_Active = 'Yes' AND tab_Sites.Si_SiteNum = '" & sqlDataReader.Item("Lo_SiteNum") & "' ORDER BY tab_Sites.Si_SiteOrder;"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                        If sqlDataReader2.Read = False Then
                                            ' BAD...
                                            Response_WriteLine("<font color=""red"">WARNING: Location " & sqlDataReader.Item("Lo_Name") & " has no active Sites.</font><br>")
                                        Else
                                            ' Good...
                                            Response_WriteLine("<font color=""green"">GOOD: Location " & sqlDataReader.Item("Lo_Name") & " has active Site " & sqlDataReader2.Item("Si_Name") & ".</font><br>")
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        If cntr = 0 Then
                            Response_WriteLine("<font color=""red"">WARNING: There are no Active Locations.</font><br>")
                        End If
                    End If ' SubType

                    If SubType = "LocNoTeam" Then
                        ' Display a warning if a Location (w/ active=Yes) has no Teams (w/ active=Yes)
                        If Me.AdminSite = "000" Then
                            ' show all Sites
                            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_Active = 'Yes' ORDER BY tab_Locations.Lo_SortOrder;"
                        Else
                            ' show only this Site
                            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_Active = 'Yes' AND tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Locations.Lo_SortOrder;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    sSqlString = "SELECT COUNT(tab_Teams.Te_Index) AS THECOUNT FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & sqlDataReader.Item("Lo_Index") & " AND tab_Teams.Te_Active = 'Yes';"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader
                                        sqlDataReader2.Read()
                                        If sqlDataReader2.Item("THECOUNT") = 0 Then
                                            ' BAD...
                                            Response_WriteLine("<font color=""red"">WARNING: Location " & sqlDataReader.Item("Lo_Name") & " has 0 Teams.</font><br>")
                                        Else
                                            ' Good...
                                            If sqlDataReader2.Item("THECOUNT") = 1 Then
                                                Response_WriteLine("<font color=""green"">GOOD: Location " & sqlDataReader.Item("Lo_Name") & " has 1 Team.</font><br>")
                                            Else
                                                Response_WriteLine("<font color=""green"">GOOD: Location " & sqlDataReader.Item("Lo_Name") & " has " & sqlDataReader2.Item("THECOUNT") & " Teams.</font><br>")
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If ' SubType

                    If SubType = "TeamNoLoc" Then
                        ' Display a warning if a Team (w/ active=Yes) has no Locations (w/ active=Yes)
                        cntr = 0
                        If Me.AdminSite = "000" Then
                            ' show all Sites
                            sSqlString = "Select tab_Teams.Te_LocationIndex, tab_Teams.Te_Name FROM tab_Teams WHERE tab_Teams.Te_Active = 'Yes' ORDER BY tab_Teams.Te_LocationIndex, tab_Teams.Te_Name;"
                        Else
                            ' show only this Site
                            sSqlString = "SELECT tab_Teams.Te_LocationIndex, tab_Teams.Te_Name FROM tab_Teams LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Teams.Te_Active = 'Yes' AND tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Teams.Te_LocationIndex, tab_Teams.Te_Name;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    cntr = cntr + 1
                                    sSqlString = "SELECT tab_Locations.Lo_Name FROM tab_Locations WHERE tab_Locations.Lo_Index = " & sqlDataReader.Item("Te_LocationIndex") & " AND tab_Locations.Lo_Active = 'Yes';"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                        If sqlDataReader2.Read = False Then
                                            ' BAD...
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                Response_WriteLine("<font color=""red"">WARNING: Team " & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & " has no active Locations.</font><br>")
                                            Else
                                                Response_WriteLine("<font color=""red"">WARNING: Team " & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & " has no active Locations.</font><br>")
                                            End If
                                        Else
                                            ' Good...
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                Response_WriteLine("<font color=""green"">GOOD: Team  " & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & " has active Location " & sqlDataReader2.Item("Lo_Name") & ".</font><br>")
                                            Else
                                                Response_WriteLine("<font color=""green"">GOOD: Team  " & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & " has active Location " & sqlDataReader2.Item("Lo_Name") & ".</font><br>")
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        If cntr = 0 Then
                            Response_WriteLine("<font color=""red"">WARNING: There are no Active Teams.</font><br>")
                        End If
                    End If ' SubType

                    If SubType = "TeamNoMem" Then
                        ' Display a warning if a Team (w/ active=Yes) has no members (w/ active=Yes)
                        If Me.AdminSite = "000" Then
                            ' show all Sites
                            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_LocationIndex, tab_Teams.Te_Name FROM tab_Teams WHERE tab_Teams.Te_Active = 'Yes' ORDER BY tab_Teams.Te_LocationIndex, tab_Teams.Te_SortOrder;"
                        Else
                            ' show only this Site
                            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_LocationIndex, tab_Teams.Te_Name FROM tab_Teams LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Teams.Te_Active = 'Yes' AND tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "' ORDER BY tab_Teams.Te_LocationIndex, tab_Teams.Te_SortOrder;"
                        End If

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    sSqlString = "SELECT COUNT(tab_Members.Me_Index) AS THECOUNT FROM tab_Members WHERE tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Te_Index") & " AND tab_Members.Me_Active = 'Yes';"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                        If sqlDataReader2.Read = True Then
                                            If sqlDataReader2.Item("THECOUNT") = 0 Then
                                                ' BAD...
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine("<font color=""red"">WARNING: Team " & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & " - " & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & " has no Members.</font><br>")
                                                Else
                                                    Response_WriteLine("<font color=""red"">WARNING: Team " & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & " - " & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & " has no Members.</font><br>")
                                                End If
                                            Else
                                                ' Good...
                                                If sqlDataReader2.Item("THECOUNT") = 1 Then
                                                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                        Response_WriteLine("<font color=""green"">GOOD: Team " & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & " - " & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & " has 1 Member.</font><br>")
                                                    Else
                                                        Response_WriteLine("<font color=""green"">GOOD: Team " & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & " - " & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & " has 1 Member.</font><br>")
                                                    End If
                                                Else
                                                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                        Response_WriteLine("<font color=""green"">GOOD: Team " & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & " - " & Me.ColorizeTeamName(sqlDataReader.Item("Te_Name")) & " has " & sqlDataReader2.Item("THECOUNT") & " Members.</font><br>")
                                                    Else
                                                        Response_WriteLine("<font color=""green"">GOOD: Team " & Me.GetLocationName(sqlDataReader.Item("Te_LocationIndex")) & " - " & Me.ColorizeFont(sqlDataReader.Item("Te_Name")) & " has " & sqlDataReader2.Item("THECOUNT") & " Members.</font><br>")
                                                    End If
                                                End If
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                    End If ' SubType

                    If SubType = "MemNoTeam" Then
                        ' Display a warning if a Member (w/ active=Yes) has no Teams (w/ active=Yes)
                        cntr = 0
                        sSqlString = "Select tab_Members.Me_TeamIndex, tab_Members.Me_Name, tab_Members.Me_Title FROM tab_Members WHERE tab_Members.Me_Active = 'Yes' ORDER BY tab_Members.Me_TeamIndex, tab_Members.Me_Name;"

                        MyCommand.CommandText = sSqlString

                        Try
                            If MyConnection.State = ConnectionState.Closed Then
                                MyConnection.Open()
                            End If

                            sqlDataReader = MyCommand.ExecuteReader

                            If sqlDataReader.HasRows = True Then
                                While sqlDataReader.Read = True
                                    cntr = cntr + 1
                                    sSqlString = "SELECT tab_Teams.Te_LocationIndex, tab_Teams.Te_Name, tab_Teams.Te_Active, tab_Locations.Lo_SiteNum FROM" & " tab_Teams LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index" & " WHERE tab_Teams.Te_Index = " & sqlDataReader.Item("Me_TeamIndex") & ";"

                                    MyCommand2.CommandText = sSqlString

                                    Try
                                        If MyConnection2.State = ConnectionState.Closed Then
                                            MyConnection2.Open()
                                        End If

                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                        If sqlDataReader2.Read = False Then
                                            ' BAD...
                                            Response_WriteLine("<font color=""red"">WARNING: Member " & sqlDataReader.Item("Me_Name") & "")
                                            If Not IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                                Response_WriteLine("&nbsp;" & sqlDataReader.Item("Me_Title") & "")
                                            End If
                                            Response_WriteLine("has <b>invalid</b> TeamIndex</font><br>")
                                        Else
                                            If Not IsDBNull(sqlDataReader2.Item("Lo_SiteNum")) Then
                                                If sqlDataReader2.Item("Lo_SiteNum") = Me.AdminSite Or Me.AdminSite = "000" Then
                                                    If sqlDataReader2.Item("Te_Active") = "No" Then
                                                        ' BAD...
                                                        Response_WriteLine("<font color=""navy"">NOTE: Member " & sqlDataReader.Item("Me_Name") & "")
                                                        If Not IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                                            Response_WriteLine("&nbsp;" & sqlDataReader.Item("Me_Title") & "")
                                                        End If
                                                        Response_WriteLine("has no active Team.</font><br>")
                                                    Else
                                                        ' Good...
                                                        ' don't need to display good members, there are too many
                                                        ' <font color="green">GOOD: Member =sqlDataReader.Item("Me_Name") has active Team =GetLocationName(rs2("Te_LocationIndex")) - =rs2("Te_Name").</font><br>
                                                    End If
                                                Else
                                                    ' ignore, different site, so don't show it.
                                                End If
                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                End While
                            End If

                        Catch ex As Exception
                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                        Finally
                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                        End Try

                        If cntr = 0 Then
                            Response_WriteLine("<font color=""red"">WARNING: There are no Active Members.</font><br>")
                        End If
                    End If 'SubType
                End If 'Relationships

            Case "ViewAdmin"
                '
                ' VIEW ADMIN SETUP
                '
                ' ViewAdmin, ViewTeam, ViewMember are split because when combined the lengthy ShowMembers() will cause the IIS server buffer to be too big and the page hangs
                ' Globals Table
                sSqlString = "SELECT * FROM tab_Globals;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = True Then
                        Response_WriteLine("<p>")
                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                        Response_WriteLine("<Table class=""table table-striped table-bordered table-hover table-condensed"">")
                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""2"">Table_Globals</th></tr>")
                        Response_WriteLine("<tr style=""vertical-align:top""><td bgcolor=""#eeeeee"">adminEmailAddress</td><td>" & sqlDataReader.Item("Gl_adminEmailAddress") & "</td></tr>")
                        Response_WriteLine("<tr style=""vertical-align:top""><td bgcolor=""#eeeeee"">webURL</td><td>" & sqlDataReader.Item("Gl_webURL") & "</td></tr>")
                        Response_WriteLine("<tr style=""vertical-align:top""><td bgcolor=""#eeeeee"">webAdminURL</td><td>" & sqlDataReader.Item("Gl_webAdminURL") & "</td></tr>")
                        Response_WriteLine("<tr style=""vertical-align:top""><td bgcolor=""#eeeeee"">webName</td><td>" & sqlDataReader.Item("Gl_webName") & "</td></tr>")
                        Response_WriteLine("<tr style=""vertical-align:top""><td bgcolor=""#eeeeee"">emailActive</td><td>" & sqlDataReader.Item("Gl_emailActive") & "</td></tr>")
                        Response_WriteLine("<tr style=""vertical-align:top""><td bgcolor=""#eeeeee"">emailServer</td><td>" & sqlDataReader.Item("Gl_emailServer") & "</td></tr>")
                        Response_WriteLine("</table>")
                        Response_WriteLine("</td></tr></table>")
                        Response_WriteLine("</p>")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                ' Reasons Table
                sSqlString = "SELECT * FROM tab_Reasons ORDER BY tab_Reasons.Re_Type, tab_Reasons.Re_SortOrder;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.Read = True Then
                        cntr = 0
                        Response_WriteLine("<p>")
                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                        Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"">")
                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""6"">Table_Reasons</th></tr>")
                        Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                        Response_WriteLine("<th>Index</th>")
                        Response_WriteLine("<th>Type</th>")
                        Response_WriteLine("<th>SortOrder</th>")
                        Response_WriteLine("<th>Active</th>")
                        Response_WriteLine("<th>Name</th>")
                        Response_WriteLine("<th>Notes</th>")
                        Response_WriteLine("</tr>")
                        While sqlDataReader.Read = True
                            If cntr Mod 2 = 0 Then
                                Response_WriteLine("<tr style=""vertical-align:top"">")
                            Else
                                Response_WriteLine("<tr style=""vertical-align:top"" bgcolor=whitesmoke>")
                            End If
                            Response_WriteLine("<td>" & sqlDataReader.Item("Re_Index") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Re_Type") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Re_SortOrder") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Re_Active") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Re_Name") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Re_Notes") & "</td>")
                            Response_WriteLine("</tr>")
                            cntr = cntr + 1
                        End While
                        Response_WriteLine("</table>")
                        Response_WriteLine("</td></tr></table>")
                        Response_WriteLine("</p>")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                ' Titles Table
                sSqlString = "SELECT * FROM tab_Titles ORDER BY tab_Titles.Ti_SortOrder;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If sqlDataReader.HasRows = True Then
                        cntr = 0
                        Response_WriteLine("<p>")
                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                        Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed"">")
                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Table_Titles</th></tr>")
                        Response_WriteLine("<tr bgcolor=""#eeeeee"">")
                        Response_WriteLine("<th>SortOrder</th>")
                        Response_WriteLine("<th>Title</th>")
                        Response_WriteLine("<th>Description</th>")
                        Response_WriteLine("</tr>")
                        While sqlDataReader.Read = True
                            If cntr Mod 2 = 0 Then
                                Response_WriteLine("<tr style=""vertical-align:top"">")
                            Else
                                Response_WriteLine("<tr style=""vertical-align:top"" bgcolor=whitesmoke>")
                            End If
                            Response_WriteLine("<td>" & sqlDataReader.Item("Ti_SortOrder") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Ti_Title") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("Ti_Description") & "</td>")
                            Response_WriteLine("</tr>")
                            cntr = cntr + 1
                        End While
                        Response_WriteLine("</table>")
                        Response_WriteLine("</td></tr></table>")
                        Response_WriteLine("</p>")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

                ' Scripts Table  
                '   -1 means don't highlight any of the locations
                Me.ShowScriptsTable(-1)

                ' Admins Table
                Me.ShowAdminsTable(Me.UserName)

                ' AD Groups Table
                Me.ShowADGroupsTable(Me.AdminSite)

                ' Holidays Table
                Me.ShowHolidaysTable()

            Case "ViewTeam"
                '
                ' VIEW TEAM SETUP
                '
                ' ViewAdmin, ViewTeam, ViewMember are split because when combined the lengthy ShowMembers() will cause the IIS server buffer to be too big and the page hangs

                ' Sites Table
                Me.ShowSitesTable(Me.AdminSite)

                ' Locations Table
                Me.ShowLocationsTable(Me.AdminSite)

                ' Teams Table
                Me.ShowTeamsTable("")

            Case "ViewMember"
                '
                ' VIEW MEMBER SETUP
                '
                ' ViewAdmin, ViewTeam, ViewMember are split because when combined the lengthy ShowMembers() will cause the IIS server buffer to be too big and the page hangs

                ' Members table is very large so flush the buffer first to prevent reaching buffer size limits	
                If Response.Buffer = True Then
                    'Note: If response.Buffer is false, then Response.Flush and Response.Clear will cause a run-time error.
                    Response.Flush()
                    Response.Clear()
                End If

                ' Members Table
                Me.ShowMembersTable(0, "")

            Case "Edit"
                '
                ' EDIT SETUP
                '

                Dim optionCount, optionItem
                Dim EditType, form_Choice, form_Method
                If (Not Request.QueryString("EditType") Is Nothing) Then EditType = Request.QueryString("EditType").ToString() Else EditType = ""
                form_Choice = Request.Form("form_Choice")
                form_Method = Request.Form("form_Method")

                If _clsMessageVAR.BDebug = True Then
                    Response.Write("form_Choice=" & form_Choice & "<br>")
                    Response.Write("form_Method=" & form_Method & "<br>")
                End If

                If form_Choice = "" Then
                    ' NEW FIRST entry - list choices for editing method
                    Response_WriteLine("<script language=""javascript"">")
                    Response_WriteLine("				function ValidateAddLocation() {")
                    Response_WriteLine("					if (document.frmChoiceAddLocation.idSiteNum.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Add Location Error\rChoose a site and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateAddTeam() {")
                    Response_WriteLine("					if (document.frmChoiceAddTeam.idLocationIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Add Team Error\rChoose a location and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateAddMember() {")
                    Response_WriteLine("					if ((document.frmChoiceAddMember.idTeamIndex.selectedIndex == 0) || (document.frmChoiceAddMember.idTeamIndex.selectedIndex == -1)) {")
                    Response_WriteLine("						// .selectedIndex = 0 = ""--- Select Multiple---""")
                    Response_WriteLine("						// .selectedIndex = -1 = nothing chosen")
                    Response_WriteLine("						// .value = """" nothing chosen")
                    Response_WriteLine("						alert(""Add Member Error\rChoose a Team and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateAddScript() {")
                    Response_WriteLine("					if (document.frmChoiceAddScript.idLocationIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Add Script Error\rChoose a location and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditSite() {")
                    Response_WriteLine("					if (document.frmChoiceEditSite.idSiteNum.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Site Error\rChoose a Site and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditLocation() {")
                    Response_WriteLine("					if (document.frmChoiceEditLocation.idLocationIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Location Error\rChoose a Location and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditTeam() {")
                    Response_WriteLine("					if (document.frmChoiceEditTeam.idTeamIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Team Error\rChoose a Team and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditMember() {")
                    Response_WriteLine("					if (document.frmChoiceEditMember.idMemberIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Member Error\rChoose a Member and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditAdmin() {")
                    Response_WriteLine("					if (document.frmChoiceEditAdmin.idAdminUsername.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Admin Error\rChoose an Admin and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditADGroup() {")
                    Response_WriteLine("					if (document.frmChoiceEditADGroup.idName.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit AD Group Error\rChoose an Admin and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditScript() {")
                    Response_WriteLine("					if (document.frmChoiceEditScript.idScriptIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Script Error\rChoose a Script and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateEditHoliday() {")
                    Response_WriteLine("					if (document.frmChoiceEditHoliday.idHoDate.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Edit Holiday Error\rChoose a Date and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveSite() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveSite.idSiteNum.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Site Error\rChoose a Site and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveLocation() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveLocation.idLocationIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Location Error\rChoose a Location and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveTeam() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveTeam.idTeamIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Team Error\rChoose a valid Team and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveMember() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveMember.idMemberIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Member Error\rChoose a Member and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveAdmin() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveAdmin.idAdminUsername.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Admin Error\rChoose an Admin and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveADGroup() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveADGroup.idName.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove AD Group Error\rChoose an AD Group and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveScript() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveScript.idScriptIndex.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Script Error\rChoose a Script and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("				function ValidateRemoveHoliday() {")
                    Response_WriteLine("					if (document.frmChoiceRemoveHoliday.idHoDate.selectedIndex == 0) {")
                    Response_WriteLine("						alert(""Remove Holiday Error\rChoose a Date and submit again."");")
                    Response_WriteLine("						return false;")
                    Response_WriteLine("					} else {")
                    Response_WriteLine("						return true;")
                    Response_WriteLine("					}")
                    Response_WriteLine("				}")
                    Response_WriteLine("			</script>")
                    Response_WriteLine("<p>")
                    Response_WriteLine("<a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&EditType=Add"">")
                    If EditType = "Add" Then
                        Response_WriteLine("<b>Add</b>")
                    Else
                        Response_WriteLine("Add")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&EditType=Edit"">")
                    If EditType = "Edit" Then
                        Response_WriteLine("<b>Edit</b>")
                    Else
                        Response_WriteLine("Edit")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("- <a href=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & "&EditType=Remove"">")
                    If EditType = "Remove" Then
                        Response_WriteLine("<b>Remove</b>")
                    Else
                        Response_WriteLine("Remove")
                    End If
                    Response_WriteLine("</a>")
                    Response_WriteLine("</p>")
                    Select Case EditType
                        Case "Add"

                            ' ADD section - BEGIN
                            Response_WriteLine("<p>")
                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td><table>")
                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">ADD</th></tr>")
                            ' Add a Site
                            If Me.AdminSite = "000" Then
                                Response_WriteLine("<form name=""frmChoiceAddSite"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<tr>")
                                Response_WriteLine("<td bgcolor=""#d6dbe9"">Site</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddSite"">")
                                Response_WriteLine("</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Site"" style=""width:240;font-size:14"">")
                                Response_WriteLine("</td>")
                                Response_WriteLine("</tr>")
                                Response_WriteLine("</form>")
                            Else
                                ' cannot add a site with only site level access
                            End If


                            ' Add a Location
                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000'"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " AND tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceAddLocation"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateAddLocation();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Location</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddLocation"">")
                                    Response_WriteLine("<select name=""form_SiteNum"" id=""idSiteNum"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Si_SiteNum") & """>")
                                        If sqlDataReader.Item("Si_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Si_SiteNum") & "-" & sqlDataReader.Item("Si_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Location to this Site"" style=""width:240;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Add a Team
                            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceAddTeam"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateAddTeam();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Team</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddTeam"">")
                                    Response_WriteLine("<select name=""form_LocationIndex"" id=""idLocationIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Lo_Index") & """>")
                                        If sqlDataReader.Item("Lo_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Team to this Location"" style=""width:240;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Add a Member
                            optionItem = ""
                            optionCount = 0
                            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_Name, tab_Teams.Te_Active, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name" & " FROM tab_Locations LEFT JOIN tab_Teams ON tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceAddMember"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateAddMember();"" style=""margin:0"">")
                                    Response_WriteLine("<tr valign=""top"">")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Member</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                    While sqlDataReader.Read = True
                                        If IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                            ' No Team exists for this Location so don't show it
                                        Else
                                            optionItem = optionItem & "<option value=""" & sqlDataReader.Item("Te_Index") & """>"
                                            If sqlDataReader.Item("Te_Active") = "No" Then
                                                optionItem = optionItem & "* "
                                            End If
                                            optionItem = optionItem & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & "</option>" & vbCrLf
                                            optionCount = optionCount + 1
                                        End If
                                    End While
                                    If optionCount > 1 Then
                                        optionItem = "<option value="""">--- Select Multiple ---</option>" & optionItem & vbCrLf
                                    Else
                                        optionItem = "<option value=""""></option>" & optionItem & vbCrLf
                                    End If
                                    If optionCount >= 9 Then
                                        optionCount = 10
                                    Else
                                        optionCount = optionCount + 1
                                    End If
                                    Response_WriteLine("<select name=""form_TeamIndex"" id=""idTeamIndex"" class=""form-control"" multiple size=""" & optionCount & """>")
                                    Response_WriteLine("" & optionItem & "")
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Member to 1 or more Teams"" style=""width:240;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Add an Admin
                            Response_WriteLine("<form name=""frmChoiceAddAdmin"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"">Admin</td>")
                            Response_WriteLine("<td>")
                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddAdmin"">")
                            Response_WriteLine("</td>")
                            Response_WriteLine("<td>")
                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Admin"" style=""width:240;font-size:14"">")
                            Response_WriteLine("</td>")
                            Response_WriteLine("</tr>")
                            Response_WriteLine("</form>")
                            ' Add an AD Group
                            Response_WriteLine("<form name=""frmChoiceAddADGroup"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                            Response_WriteLine("<tr>")
                            Response_WriteLine("<td bgcolor=""#d6dbe9"">Group</td>")
                            Response_WriteLine("<td>")
                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddADGroup"">")
                            Response_WriteLine("</td>")
                            Response_WriteLine("<td>")
                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Group"" style=""width:240;font-size:14"">")
                            Response_WriteLine("</td>")
                            Response_WriteLine("</tr>")
                            Response_WriteLine("</form>")
                            ' Add a Script
                            ' Show all Locations even if they have scripts already because next step chooses the available reasons
                            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceAddScript"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateAddScript();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Script</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddScript"">")
                                    Response_WriteLine("<select name=""form_LocationIndex"" id=""idLocationIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    If Me.AdminSite = "000" Then
                                        ' only system wide admins get the Default choice
                                        Response_WriteLine("<option value=""0"">--- Default ---</option>")
                                    End If
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Lo_Index") & """>")
                                        If sqlDataReader.Item("Lo_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Script to this Location"" style=""width:240;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Add a Holiday
                            If Me.AdminSite = "000" Then
                                ' only system wide admins get the Holiday menu
                                Response_WriteLine("<form name=""frmChoiceAddHoliday"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<tr>")
                                Response_WriteLine("<td bgcolor=""#d6dbe9"">Holiday</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddHoliday"">")
                                Response_WriteLine("</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Holiday"" style=""width:240;font-size:14"">")
                                Response_WriteLine("</td>")
                                Response_WriteLine("</tr>")
                                Response_WriteLine("</form>")
                            End If

                            ' Add a Global
                            ' single row only: edit only, and edit in database

                            ' Add a Reason
                            ' ReasonType CANNOT have a quote (") in it.
                            ' FEE, PACT, etc

                            ' Add a Title
                            ' Edit the database directly.
                            ' Title CANNOT have a quote (") in it.

                            ' Add a Flag
                            ' Edit the database directly
                            ' This can be adjusted, reduced, increased at any time but it applies to all sites.

                            ' ADD section - END
                            Response_WriteLine("</table></td></tr>")
                            Response_WriteLine("</table>")
                            Response_WriteLine("</p>")
                        Case "Edit"
                            ' EDIT section - BEGIN
                            Response_WriteLine("<p>")
                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td><table>")
                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">EDIT</th></tr>")
                            ' Edit Site
                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000'"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " AND tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditSite"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditSite();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Site</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                    Response_WriteLine("<select name=""form_SiteNum"" id=""idSiteNum"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Si_SiteNum") & """>")
                                        If sqlDataReader.Item("Si_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Si_SiteNum") & "-" & sqlDataReader.Item("Si_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Site"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit Location
                            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditLocation"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditLocation();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Location</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                    Response_WriteLine("<select name=""form_LocationIndex"" id=""idLocationIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Lo_Index") & """>")
                                        If sqlDataReader.Item("Lo_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Location"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit Team
                            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_Name, tab_Teams.Te_Active, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name" & " FROM tab_Locations LEFT JOIN tab_Teams ON tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditTeam"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditTeam();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Team</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                    Response_WriteLine("<select name=""form_TeamIndex"" id=""idTeamIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        If IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                            ' No Team exists for this Location so don't show it
                                        Else
                                            If sqlDataReader.Item("Te_Active") = "Yes" Then
                                                Response_WriteLine("<option value=""" & sqlDataReader.Item("Te_Index") & """>")
                                                Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & "</option>")
                                            End If
                                        End If
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Team"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit Member
                            sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_Name, tab_Members.Me_Title, tab_Members.Me_Active, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Teams.Te_Name" & " FROM (tab_Members LEFT JOIN tab_Teams ON tab_Members.Me_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Members.Me_SortOrder, tab_Members.Me_Name;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditMember"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditMember();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Member</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                    Response_WriteLine("<select name=""form_MemberIndex"" id=""idMemberIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Me_Index") & """>")
                                        If sqlDataReader.Item("Me_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & "-" & sqlDataReader.Item("Me_Name") & "")
                                        If Not IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                            Response_WriteLine("&nbsp;" & sqlDataReader.Item("Me_Title") & "")
                                        End If
                                        Response_WriteLine("</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Member"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit Admin
                            If Me.AdminSite = "000" Then
                                ' show all Sites
                                sSqlString = "SELECT tab_Admins.Adm_Username, tab_Admins.Adm_Name, tab_Admins.Adm_SiteNum, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type FROM tab_Admins"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                    sSqlString = sSqlString & " WHERE tab_Admins.Adm_SiteNum IN(" & Me.AdminSites & ",'000')"
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Admins.Adm_SiteNum IN(" & Me.AdminSites & ",'000') AND tab_Admins.Adm_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Admins.Adm_SiteNum, tab_Admins.Adm_Type, tab_Admins.Adm_AccessLevel DESC, tab_Admins.Adm_Username;"
                            Else
                                ' show only this Site
                                sSqlString = "SELECT tab_Admins.Adm_Username, tab_Admins.Adm_Name, tab_Admins.Adm_SiteNum, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type FROM tab_Admins" & " WHERE tab_Admins.Adm_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Admins.Adm_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Admins.Adm_Type, tab_Admins.Adm_AccessLevel DESC, tab_Admins.Adm_Username;"
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditAdmin"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditAdmin();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Admin</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditAdmin"">")
                                    Response_WriteLine("<select name=""form_Username"" id=""idAdminUsername"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Adm_Username") & """>" & sqlDataReader.Item("Adm_SiteNum") & ":" & sqlDataReader.Item("Adm_Type") & ":" & sqlDataReader.Item("Adm_AccessLevel") & "-" & sqlDataReader.Item("Adm_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Admin"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit AD Group
                            If Me.AdminSite = "000" Then
                                ' show all Sites
                                sSqlString = "SELECT tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName, tab_ADGroups.AD_Type FROM tab_ADGroups"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_ADGroups.AD_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_Type, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName;"
                            Else
                                ' show only this Site
                                sSqlString = "SELECT tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName, tab_ADGroups.AD_Type FROM tab_ADGroups" & " WHERE tab_ADGroups.AD_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_ADGroups.AD_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_ADGroups.AD_Type, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName;"
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditADGroup"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditADGroup();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Group</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditADGroup"">")
                                    Response_WriteLine("<select name=""form_Name"" id=""idName"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & Replace(sqlDataReader.Item("AD_GroupName"), """", "&#34;") & """>" & sqlDataReader.Item("AD_SiteNum") & ":" & sqlDataReader.Item("AD_Type") & ":" & sqlDataReader.Item("AD_AccessLevel") & "-" & sqlDataReader.Item("AD_GroupName") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Group"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit Script
                            sSqlString = "SELECT tab_Scripts.Sc_Index, tab_Scripts.Sc_LocationIndex," & " tab_Reasons.Re_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active" & " FROM (tab_Scripts LEFT JOIN tab_Reasons ON tab_Scripts.Sc_ReasonIndex = tab_Reasons.Re_Index)" & " LEFT JOIN tab_Locations ON tab_Scripts.Sc_LocationIndex = tab_Locations.Lo_Index"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                ' only system wide admins can edit the Default value, meaning 000 is not shown due to this WHERE clause
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Reasons.Re_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceEditScript"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditScript();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Script</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditScript"">")
                                    Response_WriteLine("<select name=""form_ScriptIndex"" id=""idScriptIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        If sqlDataReader.Item("Sc_LocationIndex") = 0 Then
                                            ' default
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Sc_Index") & """>Default-" & sqlDataReader.Item("Re_Name") & "</option>")
                                        Else
                                            If Not IsDBNull(sqlDataReader.Item("Lo_SiteNum")) Then
                                                Response_WriteLine("<option value=""" & sqlDataReader.Item("Sc_Index") & """>")
                                                If sqlDataReader.Item("Lo_Active") = "No" Then
                                                    Response_WriteLine("* ")
                                                End If
                                                Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Re_Name") & "</option>")
                                            End If
                                        End If
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Script"" style=""width:160;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Edit Holiday
                            If Me.AdminSite = "000" Then
                                ' only system wide admins get the Holiday menu
                                sSqlString = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays ORDER BY Ho_Date DESC;"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        ' none found, don't show
                                    Else
                                        Response_WriteLine("<form name=""frmChoiceEditHoliday"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateEditHoliday();"" style=""margin:0"">")
                                        Response_WriteLine("<tr>")
                                        Response_WriteLine("<td bgcolor=""#d6dbe9"">Holiday</td>")
                                        Response_WriteLine("<td align=""right"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditHoliday"">")
                                        Response_WriteLine("<select name=""form_HoDate"" id=""idHoDate"" class=""form-control"">")
                                        Response_WriteLine("<option></option>")
                                        While sqlDataReader.Read = True
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Ho_Date") & """>" & sqlDataReader.Item("Ho_Date") & "-" & sqlDataReader.Item("Ho_Name") & "</option>")
                                        End While
                                        Response_WriteLine("</select>")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("<td>")
                                        Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Holiday"" style=""width:160;font-size:14"">")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("</form>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                ' only system wide admins get the Field Overrides menu
                                sSqlString = "SELECT tab_Globals.Gl_overrideLName, tab_Globals.Gl_overrideFName, tab_Globals.Gl_overrideL4, tab_Globals.Gl_overridePhone, tab_Globals.Gl_overrideRCall, tab_Globals.Gl_overrideReason, tab_Globals.Gl_overrideComment, tab_Globals.Gl_overrideDOB, tab_Globals.Gl_overrideTeamColorize FROM tab_Globals;"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        ' none found, and this would be bad since there can be one and only 1 record !_!
                                    Else
                                        'Response_WriteLine("<form name=""frmEditOverrides"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return updateOverrides();"" style=""margin:0"">")
                                        Response_WriteLine("<tr>")
                                        Response_WriteLine("<td bgcolor=""#d6dbe9"">Overrides</td>")
                                        Response_WriteLine("<td align=""center"">")
                                        'Response_WriteLine("<option></option>")
                                        Response_WriteLine("<p><div class=""000 box"" style=""width:100%;border:1px solid #58589d;background-color: #fff;""><strong style=""color: #ff0000;"">Messages Field Overrides:</strong>")
                                        Response_WriteLine("<fieldset style=""width:190px;display:table;vertical-align:middle;text-align:left;"">")
                                        While sqlDataReader.Read = True
                                            ' Patient Last Name
                                            If sqlDataReader.Item("Gl_overrideLName") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideLName"">&nbsp;Patient Last Name</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideLName"">&nbsp;Patient Last Name</input><br/>")
                                            End If
                                            ' Patient First Name
                                            If sqlDataReader.Item("Gl_overrideFName") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideFName"">&nbsp;Patient First Name</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideFName"">&nbsp;Patient First Name</input><br/>")
                                            End If
                                            ' Patient Last Four SSN
                                            If sqlDataReader.Item("Gl_overrideL4") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideL4"">&nbsp;Patient Last Four SSN</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideL4"">&nbsp;Patient Last Four SSN</input><br/>")
                                            End If
                                            ' Patient Phone Number
                                            If sqlDataReader.Item("Gl_overridePhone") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overridePhone"">&nbsp;Patient Phone Number</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overridePhone"">&nbsp;Patient Phone Number</input><br/>")
                                            End If
                                            ' Patient Return Call
                                            If sqlDataReader.Item("Gl_overrideRCall") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideRCall"">&nbsp;Patient Return Call</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideRCall"">&nbsp;Patient Return Call</input><br/>")
                                            End If
                                            ' Patient Reason
                                            If sqlDataReader.Item("Gl_overrideReason") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideReason"">&nbsp;Patient Reason</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideReason"">&nbsp;Patient Reason</input><br/>")
                                            End If
                                            ' Patient Comment
                                            If sqlDataReader.Item("Gl_overrideComment") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideComment"">&nbsp;Patient Comment</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideComment"">&nbsp;Patient Comment</input><br/>")
                                            End If
                                            ' Patient Date of Birth
                                            If sqlDataReader.Item("Gl_overrideDOB") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideDOB"">&nbsp;Patient Date of Birth</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideDOB"">&nbsp;Patient Date of Birth</input><br/>")
                                            End If
                                            ' Team Colorize options (bg color vs. font color)
                                            If sqlDataReader.Item("Gl_overrideTeamColorize") = "True" Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""Gl_overrideTeamColorize"">&nbsp;Team Name styles</input><br/>")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""Gl_overrideTeamColorize"">&nbsp;Team Name styles</input><br/>")
                                            End If
                                        End While
                                        Response_WriteLine("</fieldset>")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("<td>")
                                        Response_WriteLine("<form><input type=""button"" class=""btn btn-primary"" value=""Update Overrides"" onclick=""return updateOverrides('OVERRIDE')"" style=""width:160;font-size:14""></form>")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("</tr>")
                                        'Response_WriteLine("</form>")
                                        Response_WriteLine("</div></p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                            End If

                            ' EDIT section - END
                            Response_WriteLine("</table></td></tr>")
                            Response_WriteLine("</table>")
                            Response_WriteLine("</p>")
                        Case "Remove"
                            ' REMOVE section - BEGIN
                            Response_WriteLine("<p>")
                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td><table>")
                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">REMOVE</th></tr>")
                            ' Remove Site
                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000'"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " AND tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveSite"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveSite();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Site</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveSite"">")
                                    Response_WriteLine("<select name=""form_SiteNum"" id=""idSiteNum"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Si_SiteNum") & """>")
                                        If sqlDataReader.Item("Si_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Si_SiteNum") & "-" & sqlDataReader.Item("Si_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Site"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove Location
                            sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveLocation"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveLocation();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Location</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveLocation"">")
                                    Response_WriteLine("<select name=""form_LocationIndex"" id=""idLocationIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Lo_Index") & """>")
                                        If sqlDataReader.Item("Lo_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Location"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove Team
                            sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_Name, tab_Teams.Te_Active, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name" & " FROM tab_Locations LEFT JOIN tab_Teams ON tab_Locations.Lo_Index = tab_Teams.Te_LocationIndex"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveTeam"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveTeam();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Team</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveTeam"">")
                                    Response_WriteLine("<select name=""form_TeamIndex"" id=""idTeamIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        If IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                            ' No Team exists for this Location so don't show it
                                        Else
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Te_Index") & """>")
                                            If sqlDataReader.Item("Te_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & "</option>")
                                        End If
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Team"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove Member
                            sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_Name, tab_Members.Me_Title, tab_Members.Me_Active, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Teams.Te_Name" & " FROM (tab_Members LEFT JOIN tab_Teams ON tab_Members.Me_TeamIndex = tab_Teams.Te_Index)" & " LEFT JOIN tab_Locations ON tab_Teams.Te_LocationIndex = tab_Locations.Lo_Index"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Teams.Te_SortOrder, tab_Members.Me_SortOrder, tab_Members.Me_Name;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveMember"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveMember();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Member</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveMember"">")
                                    Response_WriteLine("<select name=""form_MemberIndex"" id=""idMemberIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Me_Index") & """>")
                                        If sqlDataReader.Item("Me_Active") = "No" Then
                                            Response_WriteLine("* ")
                                        End If
                                        Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Te_Name") & "-" & sqlDataReader.Item("Me_Name") & "")
                                        If Not IsDBNull(sqlDataReader.Item("Me_Title")) Then
                                            Response_WriteLine("&nbsp;" & sqlDataReader.Item("Me_Title") & "")
                                        End If
                                        Response_WriteLine("</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Member"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove Admin
                            If Me.AdminSite = "000" Then
                                ' show all Sites
                                sSqlString = "SELECT tab_Admins.Adm_Username, tab_Admins.Adm_Name, tab_Admins.Adm_SiteNum, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type FROM tab_Admins"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Admins.Adm_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Admins.Adm_SiteNum, tab_Admins.Adm_Type, tab_Admins.Adm_AccessLevel DESC, tab_Admins.Adm_Username;"
                            Else
                                ' show only this Site
                                sSqlString = "SELECT tab_Admins.Adm_Username, tab_Admins.Adm_Name, tab_Admins.Adm_SiteNum, tab_Admins.Adm_AccessLevel, tab_Admins.Adm_Type FROM tab_Admins" & " WHERE tab_Admins.Adm_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Admins.Adm_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Admins.Adm_Type, tab_Admins.Adm_AccessLevel DESC, tab_Admins.Adm_Username;"
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveAdmin"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveAdmin();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Admin</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveAdmin"">")
                                    Response_WriteLine("<select name=""form_Username"" id=""idAdminUsername"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & sqlDataReader.Item("Adm_Username") & """>" & sqlDataReader.Item("Adm_SiteNum") & ":" & sqlDataReader.Item("Adm_Type") & ":" & sqlDataReader.Item("Adm_AccessLevel") & "-" & sqlDataReader.Item("Adm_Name") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Admin"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove AD Group
                            If Me.AdminSite = "000" Then
                                ' show all Sites
                                sSqlString = "SELECT tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName, tab_ADGroups.AD_Type FROM tab_ADGroups"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_ADGroups.AD_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_Type, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName;"
                            Else
                                ' show only this Site
                                sSqlString = "SELECT tab_ADGroups.AD_SiteNum, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName, tab_ADGroups.AD_Type FROM tab_ADGroups" & " WHERE tab_ADGroups.AD_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_ADGroups.AD_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_ADGroups.AD_Type, tab_ADGroups.AD_AccessLevel, tab_ADGroups.AD_GroupName;"
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveADGroup"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveADGroup();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Group</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveADGroup"">")
                                    Response_WriteLine("<select name=""form_Name"" id=""idName"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        Response_WriteLine("<option value=""" & Replace(sqlDataReader.Item("AD_GroupName"), """", "&#34;") & """>" & sqlDataReader.Item("AD_SiteNum") & ":" & sqlDataReader.Item("AD_Type") & ":" & sqlDataReader.Item("AD_AccessLevel") & "-" & sqlDataReader.Item("AD_GroupName") & "</option>")
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Group"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove Script
                            sSqlString = "SELECT tab_Scripts.Sc_Index, tab_Scripts.Sc_LocationIndex," & " tab_Reasons.Re_Name, tab_Locations.Lo_SiteNum, tab_Locations.Lo_Name, tab_Locations.Lo_Active" & " FROM (tab_Scripts LEFT JOIN tab_Reasons ON tab_Scripts.Sc_ReasonIndex = tab_Reasons.Re_Index)" & " LEFT JOIN tab_Locations ON tab_Scripts.Sc_LocationIndex = tab_Locations.Lo_Index"
                            If Me.AdminSite = "000" Then
                                ' don't limit by S, meaning show all sites
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            Else
                                ' limit by chosen S
                                ' only System wide admins can remove Default scripts, meaning 000 not shown due to this WHERE clause
                                sSqlString = sSqlString & " WHERE tab_Locations.Lo_SiteNum = '" & Me.AdminSite & "'"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " AND tab_Locations.Lo_Type = '" & Me.AdminType & "'"
                                End If
                            End If
                            sSqlString = sSqlString & " ORDER BY tab_Locations.Lo_SiteNum, tab_Locations.Lo_SortOrder, tab_Reasons.Re_SortOrder;"
                            If _clsMessageVAR.BDebug = True Then
                                Response.Write("sSqlString=" & sSqlString & "<br>")
                            End If

                            MyCommand.CommandText = sSqlString

                            Try
                                If MyConnection.State = ConnectionState.Closed Then
                                    MyConnection.Open()
                                End If

                                sqlDataReader = MyCommand.ExecuteReader

                                If Not sqlDataReader.HasRows Then
                                    ' none found, don't show
                                Else
                                    Response_WriteLine("<form name=""frmChoiceRemoveScript"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveScript();"" style=""margin:0"">")
                                    Response_WriteLine("<tr>")
                                    Response_WriteLine("<td bgcolor=""#d6dbe9"">Script</td>")
                                    Response_WriteLine("<td align=""right"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveScript"">")
                                    Response_WriteLine("<select name=""form_ScriptIndex"" id=""idScriptIndex"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    While sqlDataReader.Read = True
                                        If sqlDataReader.Item("Sc_LocationIndex") = 0 Then
                                            ' default
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Sc_Index") & """>Default-" & sqlDataReader.Item("Re_Name") & "</option>")
                                        Else
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Sc_Index") & """>")
                                            If IsDBNull(sqlDataReader.Item("Lo_SiteNum")) Then
                                                Response_WriteLine("ORPHANED SCRIPT RECORD - NO ASSOCIATED LOCATION RECORD")
                                            ElseIf sqlDataReader.Item("Lo_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & sqlDataReader.Item("Lo_SiteNum") & "-" & sqlDataReader.Item("Lo_Name") & "-" & sqlDataReader.Item("Re_Name") & "</option>")
                                        End If
                                    End While
                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td>")
                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Script"" style=""width:190;font-size:14"">")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("</tr>")
                                    Response_WriteLine("</form>")
                                End If

                            Catch ex As Exception
                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                            Finally
                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                            End Try

                            ' Remove Holiday
                            If Me.AdminSite = "000" Then
                                ' only system wide admins get the Holiday menu
                                Response_WriteLine("<form name=""frmChoiceRemoveHoliday"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" onsubmit=""return ValidateRemoveHoliday();"" style=""margin:0"">")
                                Response_WriteLine("<tr>")
                                Response_WriteLine("<td bgcolor=""#d6dbe9"">Holiday</td>")
                                Response_WriteLine("<td align=""right"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveHoliday"">")
                                Response_WriteLine("<select name=""form_HoDate"" id=""idHoDate"" class=""form-control"">")
                                Response_WriteLine("<option></option>")
                                sSqlString = "SELECT tab_Holidays.Ho_Date, tab_Holidays.Ho_Name FROM tab_Holidays ORDER BY Ho_Date DESC;"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        ' none found, don't show
                                    Else
                                        While sqlDataReader.Read = True
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Ho_Date") & """>" & sqlDataReader.Item("Ho_Date") & "-" & sqlDataReader.Item("Ho_Name") & "</option>")
                                        End While
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Response_WriteLine("</select>")
                                Response_WriteLine("</td>")
                                Response_WriteLine("<td>")
                                Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Holiday"" style=""width:190;font-size:14"">")
                                Response_WriteLine("</td>")
                                Response_WriteLine("</tr>")
                                Response_WriteLine("</form>")
                            End If

                            ' REMOVE section - END
                            Response_WriteLine("</table></td></tr>")
                            Response_WriteLine("</table>")
                            Response_WriteLine("</p>")
                    End Select ' EditType = {Add, Edit, Remove}
                    Response_WriteLine("<p>")
                    Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                    Response_WriteLine("<b><big>Additional Setup</big></b><br>")
                    Response_WriteLine("<p><b>Globals</b> - Must edit the database.  This is something that should not be adjusted after the system is running</p>	")
                    Response_WriteLine("<p><b>Reasons</b> - Must edit the database.  This is something that should not be adjusted after the system is running</p>")
                    Response_WriteLine("<p><b>Titles</b> - Must edit the database.  If adjusted then also find/replace as appropriate the tab_Members.Me_Title values..</p>")
                    Response_WriteLine("<p><b>Flags</b> - Must edit the database.  This can be adjusted, reduced, increased at any time but it applies to all sites.</p>")
                    Response_WriteLine("</td></tr></table>")
                    Response_WriteLine("</p>")
                    Response_WriteLine("<p>")
                    Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                    Response_WriteLine("<b><big>""Behind-the-scenes"" checks to allow deleting</big></b><br>")
                    Response_WriteLine("<br>")
                    Response_WriteLine("<b>Remove Site</b><br>")
                    Response_WriteLine("1st check for ANY (OPEN or closed) Messages for this Location<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if ANY exist, cannot delete.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;This is because Messages are tied to the unique SiteNum of this site.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;You can instead replace the Site with something else<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;and the new name will inherit the old site's Message history<br>")
                    Response_WriteLine("2nd check for ANY (active or inactive) locations that are members of this site.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if ANY exist, cannot yet delete.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;Must first remove the locations.<br>")
                    Response_WriteLine("<br>")
                    Response_WriteLine("<b>RemoveLocation</b><br>")
                    Response_WriteLine("1st check for ANY (OPEN or closed) Messages for this Location<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if ANY exist, cannot delete.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;This is because Messages are tied to the unique index of this Location.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;You can instead replace the Location name with something else<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;and the new name will inherit the old Location's Message history<br>")
                    Response_WriteLine("2nd check for ANY (active or inactive) Teams that are members of this Location.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if ANY exist, cannot yet delete.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;Must first remove the Teams.<br>")
                    Response_WriteLine("<br>")
                    Response_WriteLine("<b>RemoveTeam</b><br>")
                    Response_WriteLine("1st check for ANY (OPEN or closed) Messages for this Team<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if ANY exist, cannot delete.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;This is because Messages are tied to the unique index of this Team.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;You can instead replace the Team name with something else<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;and the new name will inherit the old Team's Message history<br>")
                    Response_WriteLine("2nd check for ANY (active or inactive) members that are members of this Team.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if ANY exist, cannot yet delete.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;Must first remove the members.<br>")
                    Response_WriteLine("<br>")
                    Response_WriteLine("<b>RemoveMember</b><br>")
                    Response_WriteLine("Check for ANY OPEN Messages assigned to this member<br>")
                    Response_WriteLine("(Closed Assigned Messages don't matter, username is logged for prosperity)<br>")
                    Response_WriteLine("if OPEN Assigned Messages exist<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;then resolve or reassign those Messages before removing member<br>")
                    Response_WriteLine("if OPEN Assigned Messages do not exist<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if InActive Team has no other Active members.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;then suggest to remove the inactive Team too.<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;if Team is active but there are no other members<br>")
                    Response_WriteLine("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;then suggest to remove the Team too.<br>")
                    Response_WriteLine("<br>")
                    Response_WriteLine("<b>RemoveAdmin</b><br>")
                    Response_WriteLine("Note - This Admin has entries in the Audit table within the last month<br>")
                    Response_WriteLine("It is questionable if it is really safe to remove this Admin from the system:<br>")
                    Response_WriteLine("</td></tr></table>")
                    Response_WriteLine("</p>")
                Else
                    ' SECOND
                    ' FIRST entry chosen - act upon that

                    ' variables that multiple "form_Choice" cases are referencing
                    Dim form_Error, maxSortOrder, memoNotes
                    Dim safeAction, safeValue
                    Dim tempEmail, tempNames
                    Dim OrigUforTable

                    ' variables for AD structure parsing
                    Dim ADloop
                    Dim strADResults, ADrows, ADarray
                    Dim ADF, ADL, ADE, ADT, ADFULL, ADU, ADSID

                    Dim form_Submit
                    Dim form_SiteNum, form_LocationIndex, form_TeamIndex, form_MemberIndex, form_Name, form_ScriptIndex
                    Dim form_SortOrder
                    Dim form_Type, form_Title, form_Username, form_SID, form_Email
                    Dim form_EmailNew, form_EmailAssign, form_EmailStatus
                    Dim form_FlagOn, form_ShowOn, form_Active
                    Dim form_Notes, form_Access, form_Details
                    Dim form_HoDate, form_Sites

                    Dim strInjectionFree

                    ' not all of these variables are used in every select statement, but most are used in multiple cases
                    form_Submit = Request.Form("form_Submit") ' button
                    form_SiteNum = Request.Form("form_SiteNum") ' dropdown
                    form_LocationIndex = Request.Form("form_LocationIndex") ' dropdown
                    form_TeamIndex = Request.Form("form_TeamIndex") ' dropdown
                    form_MemberIndex = Request.Form("form_MemberIndex") ' dropdown
                    form_ScriptIndex = Request.Form("form_ScriptIndex") ' dropdown
                    form_SortOrder = Request.Form("form_SortOrder") ' dropdown
                    form_Name = Request.Form("form_Name") ' text
                    form_Type = Request.Form("form_Type") ' dropdown
                    form_Title = Request.Form("form_Title") ' dropdown
                    form_Username = Request.Form("form_Username") ' AD Lookup
                    form_SID = Request.Form("form_SID") ' AD Lookup
                    form_Email = Request.Form("form_Email") ' text
                    form_EmailNew = Request.Form("form_EmailNew") ' dropdown
                    form_EmailAssign = Request.Form("form_EmailAssign") ' dropdown
                    form_EmailStatus = Request.Form("form_EmailStatus") ' dropdown
                    form_FlagOn = Request.Form("form_FlagOn") ' dropdown
                    form_ShowOn = Request.Form("form_ShowOn") ' dropdown
                    form_Active = Request.Form("form_Active") ' dropdown
                    form_Notes = Request.Form("form_Notes") ' text
                    form_Sites = Request.Form("form_Sites") ' text
                    form_Access = Request.Form("form_Access") ' dropdown
                    form_Details = Request.Form("form_Details") ' text
                    form_HoDate = Request.Form("form_HoDate") ' text

                    ' do not allow Username or SiteNum to have a quote (") in it
                    form_Username = Replace(form_Username, """", "")
                    form_SiteNum = Replace(form_SiteNum, """", "")
                    ' set form_Sites to form_SiteNum if form_SiteNum is not 000 ('single site' access for Admin.)
                    If form_SiteNum <> "000" Then form_Sites = "'" & form_SiteNum & "'"

                    ADloop = Request.Form("form_AD")
                    strADResults = ""
                    ADF = ""
                    ADL = ""
                    ADE = ""
                    ADT = ""
                    ADFULL = ""
                    ADU = ""
                    ADSID = ""

                    ' test the text fields against sSqlString injection
                    strInjectionFree = ""
                    If Not Me.isValidsSqlString(form_Name) Then
                        strInjectionFree = strInjectionFree & "<b>Name:</b> " & form_Name & "<br>" & vbCrLf
                    End If
                    If Not Me.isValidsSqlString(form_Email) Then
                        strInjectionFree = strInjectionFree & "<b>Email:</b> " & form_Email & "<br>" & vbCrLf
                    End If
                    If Not Me.isValidsSqlString(form_Notes) Then
                        strInjectionFree = strInjectionFree & "<b>Notes:</b> " & form_Notes & "<br>" & vbCrLf
                    End If
                    If Not Me.isValidsSqlString(form_Details) Then
                        strInjectionFree = strInjectionFree & "<b>Details:</b> " & form_Details & "<br>" & vbCrLf
                    End If
                    If Not Me.isValidsSqlString(form_HoDate) Then
                        strInjectionFree = strInjectionFree & "<b>Holiday Date:</b> " & form_HoDate & "<br>" & vbCrLf
                    End If

                    If strInjectionFree <> "" Then
                        Response_WriteLine("<p><b><font color=orange>Press <A HREF=""javascript:history.back()"">Back</A>, correct the text and submit again.<br>")
                        Response_WriteLine("<br>")
                        Response_WriteLine("Invalid Data, not storing:</font></b></p>")
                        Response_WriteLine("<table border=""1"" cellspacing=""0"" bordercolor=""black""><tr><td>" & strInjectionFree & "</td></tr></table>")
                    Else
                        ' good, no bad sSqlString Injection fields

                        Select Case form_Choice

                            Case "AddSite"

                                If form_Method = "StoreMe" Then
                                    ' new AddSite fields submitted, store them

                                    form_Error = ""
                                    ' sort order is a drop down if there are other sites already, else a text box if new
                                    If form_SortOrder = "" Then
                                        form_Error = form_Error & " SortOrder"
                                    End If
                                    If form_SiteNum = "" Or InStr(form_SiteNum, " ") Then
                                        form_Error = form_Error & " SiteNum"
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to insert

                                        sSqlString = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum LIKE '" & Replace(form_SiteNum, "'", "''") & "';"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.HasRows Then
                                                ' truly is safe, it doesn't exist yet.

                                                ' first compute correct sortorder
                                                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                                                ' when ZZZ, remove ZZZ and insert as is.
                                                ' when AAA, shift all existing sites down one.
                                                If InStr(form_SortOrder, "ZZZ") Then
                                                    form_SortOrder = Replace(form_SortOrder, "ZZZ", "")
                                                End If
                                                If InStr(form_SortOrder, "AAA") Then
                                                    form_SortOrder = Replace(form_SortOrder, "AAA", "")
                                                    sSqlString = "SELECT tab_Sites.Si_SiteOrder, tab_Sites.Si_SiteNum FROM tab_Sites WHERE tab_Sites.Si_SiteOrder >= " & form_SortOrder & " ORDER BY tab_Sites.Si_SiteOrder;"
                                                    If _clsMessageVAR.BDebug = True Then
                                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                                    End If

                                                    MyCommand2.CommandText = sSqlString

                                                    Try
                                                        If MyConnection2.State = ConnectionState.Closed Then
                                                            MyConnection2.Open()
                                                        End If

                                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                                        If Not sqlDataReader2.HasRows Then
                                                            ' strange, should not get here as the form already guaranteed they would exist
                                                            Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                                        Else
                                                            Response.Write("<br>")
                                                            While sqlDataReader2.Read = True
                                                                UpdateTableRecord("UPDATE tab_Sites SET Tab_Sites.Si_SiteOrder = " & sqlDataReader2.Item("Si_SiteOrder") + 10 & " WHERE tab_Sites.Si_SiteNum = '" & sqlDataReader2.Item("Si_SiteNum") & "';")
                                                                Response.Write("SiteNum " & sqlDataReader2.Item("Si_SiteNum") & " SortOrder updated from " & sqlDataReader2.Item("Si_SiteOrder") & " to " & sqlDataReader2.Item("Si_SiteOrder") + 10 & ".<br>")
                                                            End While
                                                        End If

                                                    Catch ex As Exception
                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                    Finally
                                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                    End Try

                                                End If

                                                sSqlString = "INSERT INTO tab_Sites (Si_SiteOrder, Si_SiteNum, Si_Name, Si_Active) " & "VALUES (" & form_SortOrder & ", '" & Replace(form_SiteNum, "'", "''") & "', '" & Replace(form_Name, "'", "''") & "', '" & form_Active & "');"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                If InsertTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">New Site <i>" & form_Name & "</i> added successfully.</font><br>")
                                                    Response_WriteLine("<form name=""frmLinkAddLocationFromAS"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                    Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddLocationFromAS.submit()""><small>Add Location</small></a>")
                                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddLocation"">")
                                                    Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                                    Response_WriteLine("</form>")
                                                    Response_WriteLine("</p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">ERROR adding new Site <i>" & form_Name & "</i>.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Add Site", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' record already found for this username.  Do not add.
                                                Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE. Cannot add new Site.<br>")
                                                Response_WriteLine("SiteNum <i>" & form_SiteNum & "</i> already exists.</font></p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing/Invalid " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<table cellspacing=""0"">")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Site</th></tr>")
                                tempNames = Me.GetSiteNames(True)
                                If tempNames = "" Then
                                    tempNames = "<font color=""red"">No Sites Exist Yet</font>"
                                Else
                                    tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                End If
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Sites&nbsp;</td><td colspan=""2"">" & tempNames & "</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<form name=""form_Method_AddSite"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddSite"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                sSqlString = "SELECT tab_Sites.Si_SiteOrder, tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' ORDER BY tab_Sites.Si_SiteOrder ASC;"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">First Site will be SortOrder=10.<br>")
                                        Response_WriteLine("This is the order that the new site will appear in the list of sites.</td>")
                                    Else
                                        Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                        maxSortOrder = 10
                                        While sqlDataReader.Read = True
                                            If sqlDataReader.Item("Si_SiteOrder") > maxSortOrder Then
                                                maxSortOrder = sqlDataReader.Item("Si_SiteOrder")
                                            End If
                                            Response_WriteLine("<option value=""AAA" & sqlDataReader.Item("Si_SiteOrder") & """>" & sqlDataReader.Item("Si_SiteOrder") & " - ")
                                            If sqlDataReader.Item("Si_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & sqlDataReader.Item("Si_SiteNum") & " - " & sqlDataReader.Item("Si_Name") & "</option>")
                                        End While
                                        Response_WriteLine("<option value=""ZZZ" & 10 + maxSortOrder & """ selected>" & 10 + maxSortOrder & " - Add to End</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected<br>")
                                        Response_WriteLine("This is the order that the new site will appear in the list of sites.</td>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Response_WriteLine("</tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum&nbsp;</td><td><input type=""text"" name=""form_SiteNum"" class=""form-control"" value="""" size=""5"" maxlength=""10""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">example: 607</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" value="""" size=""30"" maxlength=""50""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">example: Madison</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td><td><select name=""form_Active"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"">No</option></select></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Site available to receive new Messages<br>")
                                Response_WriteLine("No = Site not available to receive new Messages</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Site""></center></td></tr>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p>")
                                Me.ShowSitesTable(form_SiteNum)

                            Case "AddLocation"

                                If form_Method = "StoreMe" Then
                                    ' new AddLocation fields submitted, store them

                                    form_Error = ""
                                    ' sort order is a drop down if there are other locations already, else a text box if new
                                    If form_SortOrder = "" Then
                                        form_Error = form_Error & " SortOrder"
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Type = "" Then
                                        form_Error = form_Error & " Type"
                                    Else
                                        If form_Type = "None Found" Then
                                            form_Error = form_Error & " Type(create-Types-first)"
                                        End If
                                    End If
                                    If form_Error = "" Then
                                        ' safe to insert

                                        sSqlString = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_Name LIKE '" & Replace(form_Name, "'", "''") & "' AND tab_Locations.Lo_SiteNum = '" & form_SiteNum & "';"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.HasRows Then
                                                ' truly is safe, it doesn't exist yet.

                                                ' first compute correct sortorder
                                                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                                                ' when ZZZ, remove ZZZ and insert as is.
                                                ' when AAA, shift all existing Locations down one.
                                                If InStr(form_SortOrder, "ZZZ") Then
                                                    form_SortOrder = Replace(form_SortOrder, "ZZZ", "")
                                                End If
                                                If InStr(form_SortOrder, "AAA") Then
                                                    form_SortOrder = Replace(form_SortOrder, "AAA", "")
                                                    sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder FROM tab_Locations" & " WHERE tab_Locations.Lo_SiteNum = '" & form_SiteNum & "'" & " AND tab_Locations.Lo_SortOrder >= " & form_SortOrder & " ORDER BY tab_Locations.Lo_SortOrder;"
                                                    If _clsMessageVAR.BDebug = True Then
                                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                                    End If

                                                    MyCommand2.CommandText = sSqlString

                                                    Try
                                                        If MyConnection2.State = ConnectionState.Closed Then
                                                            MyConnection2.Open()
                                                        End If

                                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                                        If Not sqlDataReader2.HasRows Then
                                                            ' strange, should not get here as the form already guaranteed they would exist
                                                            Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                                        Else
                                                            Response.Write("<br>")
                                                            While sqlDataReader2.Read = True
                                                                UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_SortOrder = " & sqlDataReader2.Item("Lo_SortOrder") + 10 & " WHERE tab_Locations.Lo_Index = " & sqlDataReader2.Item("Lo_Index") & ";")
                                                                Response.Write("Location " & sqlDataReader2.Item("Lo_Index") & " SortOrder updated from " & sqlDataReader2.Item("Lo_SortOrder") & " to " & sqlDataReader2.Item("Lo_SortOrder") + 10 & ".<br>")
                                                            End While
                                                        End If

                                                    Catch ex As Exception
                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                    Finally
                                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                    End Try

                                                End If

                                                sSqlString = "INSERT INTO tab_Locations (Lo_SortOrder, Lo_SiteNum, Lo_Name, Lo_Type, Lo_Active) " & "VALUES (" & form_SortOrder & ", '" & form_SiteNum & "', '" & Replace(form_Name, "'", "''") & "', '" & Replace(form_Type, "'", "''") & "', '" & form_Active & "');"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                If InsertTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">New Location <i>" & form_Name & "</i> added successfully.</font>")
                                                    sSqlString2 = "SELECT MAX(tab_Locations.Lo_Index) AS MAXINDEX FROM tab_Locations;"

                                                    MyCommand2.CommandText = sSqlString2

                                                    Try
                                                        If MyConnection2.State = ConnectionState.Closed Then
                                                            MyConnection2.Open()
                                                        End If

                                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                                        If sqlDataReader2.Read = True Then
                                                            Response_WriteLine("<br>")
                                                            Response_WriteLine("<form name=""frmLinkAddTeamFromAL"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddTeamFromAL.submit()""><small>Add Team</small></a>")
                                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddTeam"">")
                                                            Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & sqlDataReader2.Item("MAXINDEX") & """>")
                                                            Response_WriteLine("</form>")
                                                        End If

                                                    Catch ex As Exception
                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                    Finally
                                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                    End Try

                                                    Response_WriteLine("</p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">ERROR adding new Location <i>" & form_Name & "</i>.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Add Location", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' record already found for this username.  Do not add.
                                                Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE. Cannot add new Location.<br>")
                                                Response_WriteLine("Location Name <i>" & form_Name & "</i> already exists in this Site.</font></p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<table cellspacing=""0"">")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Location</th></tr>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td><td colspan=""2"">")
                                Response_WriteLine("<b>" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & "</b>")
                                Response_WriteLine("<form name=""frmLinkEditSiteFromAL"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromAL.submit()""><small>Edit</small></a>")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</td></tr>")
                                tempNames = Me.GetSiteLocationNames(form_SiteNum, True)
                                If tempNames = "" Then
                                    tempNames = "<font color=""red"">No Locations Exist Yet</font>"
                                Else
                                    tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                End If
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Locations&nbsp;</td><td colspan=""2"">" & tempNames & "</td></tr>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<form name=""form_Method_AddLocation"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddLocation"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                ' SiteNum passed in as a hidden form value so multiple locations can be added back-to-back for same site
                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                ' show all types in sort order
                                sSqlString = "SELECT tab_Locations.Lo_SortOrder, tab_Locations.Lo_Name, tab_Locations.Lo_Active FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & form_SiteNum & "' ORDER BY tab_Locations.Lo_SortOrder ASC;"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">First location will be SortOrder=10.<br>")
                                        Response_WriteLine("This is the order that the new location will appear in the list of locations.</td>")
                                    Else
                                        Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                        maxSortOrder = 10
                                        While sqlDataReader.Read = True
                                            If sqlDataReader.Item("Lo_SortOrder") > maxSortOrder Then
                                                maxSortOrder = sqlDataReader.Item("Lo_SortOrder")
                                            End If
                                            Response_WriteLine("<option value=""AAA" & sqlDataReader.Item("Lo_SortOrder") & """>" & sqlDataReader.Item("Lo_SortOrder") & " - ")
                                            If sqlDataReader.Item("Lo_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & sqlDataReader.Item("Lo_Name") & "</option>")
                                        End While
                                        Response_WriteLine("<option value=""ZZZ" & 10 + maxSortOrder & """ selected>" & 10 + maxSortOrder & " - Add to End</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected<br>")
                                        Response_WriteLine("This is the order that the new location will appear in the list of locations.</td>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Response_WriteLine("</tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" value="""" size=""50"" maxlength=""255""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">example: Madison West Annex</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type&nbsp;</td>")
                                Response_WriteLine("<td><select name=""form_Type"" class=""form-control"">")
                                optionCount = 0
                                optionItem = ""
                                sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Reasons.Re_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Reasons.Re_Type;"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        optionCount = 0
                                        optionItem = "<option value=""None Found"">None Found</option>" & vbCrLf
                                    Else
                                        While sqlDataReader.Read = True
                                            ' Only include PACT as par John P. TJD
                                            If sqlDataReader.Item("REASONTYPE") = "PACT" Then
                                                optionItem = optionItem & "<option value=""" & sqlDataReader.Item("REASONTYPE") & """>" & sqlDataReader.Item("REASONTYPE") & "</option>" & vbCrLf
                                                optionCount = optionCount + 1
                                            End If
                                        End While
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                If optionCount > 1 Then
                                    ' default a blank at the top so a type has to be chosen
                                    optionItem = "<option></option>" & optionItem & vbCrLf
                                Else
                                    ' insert no blank at the top
                                End If
                                Response.Write(optionItem)
                                Response_WriteLine("</select></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Choose the Type of Reasons that apply to all Teams in this Location</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td><td><select name=""form_Active"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"">No</option></select></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Location available to receive new Messages<br>")
                                Response_WriteLine("No = Location not available to receive new Messages</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Location""></center></td></tr>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p>")
                                Me.ShowLocationsTable(form_SiteNum)

                            Case "AddTeam"

                                If form_Method = "StoreMe" Then
                                    ' new AddTeam fields submitted, store them

                                    form_Error = ""
                                    If form_SortOrder = "" Then
                                        form_Error = form_Error & " SortOrder"
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Notes = "" Then
                                        form_Error = form_Error & " Notes"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to insert

                                        sSqlString = "SELECT * FROM tab_Teams WHERE tab_Teams.Te_Name LIKE '" & Replace(form_Name, "'", "''") & "' AND tab_Teams.Te_LocationIndex = " & form_LocationIndex & ";"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.HasRows Then
                                                ' truly is safe, it doesn't exist yet.

                                                ' first compute correct sortorder
                                                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                                                ' when ZZZ, remove ZZZ and insert as is.
                                                ' when AAA, shift all existing Teams down one.
                                                If InStr(form_SortOrder, "ZZZ") Then
                                                    form_SortOrder = Replace(form_SortOrder, "ZZZ", "")
                                                End If
                                                If InStr(form_SortOrder, "AAA") Then
                                                    form_SortOrder = Replace(form_SortOrder, "AAA", "")
                                                    sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder FROM tab_Teams" & " WHERE tab_Teams.Te_LocationIndex = " & form_LocationIndex & " AND tab_Teams.Te_SortOrder >= " & form_SortOrder & " ORDER BY tab_Teams.Te_SortOrder;"
                                                    If _clsMessageVAR.BDebug = True Then
                                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                                    End If

                                                    MyCommand2.CommandText = sSqlString

                                                    Try
                                                        If MyConnection2.State = ConnectionState.Closed Then
                                                            MyConnection2.Open()
                                                        End If

                                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                                        If Not sqlDataReader2.HasRows Then
                                                            ' strange, should not get here as the form already guaranteed they would exist
                                                            Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                                        Else
                                                            While sqlDataReader2.Read = True
                                                                Response.Write("<br>")
                                                                UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_SortOrder = " & sqlDataReader2.Item("Te_SortOrder") + 10 & " WHERE tab_Teams.Te_Index = " & sqlDataReader2.Item("Te_Index") & ";")
                                                                Response.Write("Team " & sqlDataReader2.Item("Te_Index") & " SortOrder updated from " & sqlDataReader2.Item("Te_SortOrder") & " to " & sqlDataReader2.Item("Te_SortOrder") + 10 & ".<br>")
                                                            End While
                                                        End If

                                                    Catch ex As Exception
                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                    Finally
                                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                    End Try

                                                End If

                                                sSqlString = "INSERT INTO tab_Teams (Te_SortOrder, Te_LocationIndex, Te_Name, Te_Active, Te_Notes) " & "VALUES (" & form_SortOrder & ", " & form_LocationIndex & ", '" & Replace(form_Name, "'", "''") & "', '" & form_Active & "', '" & Replace(form_Notes, "'", "''") & "');"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                If InsertTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">New Team <i>" & form_Name & "</i> added successfully.</font>")
                                                    sSqlString2 = "SELECT MAX(tab_Teams.Te_Index) AS MAXINDEX FROM tab_Teams;"

                                                    MyCommand2.CommandText = sSqlString2

                                                    Try
                                                        If MyConnection2.State = ConnectionState.Closed Then
                                                            MyConnection2.Open()
                                                        End If

                                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                                        If sqlDataReader2.Read = True Then
                                                            Response_WriteLine("<br>")
                                                            Response_WriteLine("<form name=""frmLinkAddMemberFromAT"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddMemberFromAT.submit()""><small>Add Member</small></a>")
                                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                                            Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & sqlDataReader2.Item("MAXINDEX") & """>")
                                                            Response_WriteLine("</form>")
                                                        End If

                                                    Catch ex As Exception
                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                    Finally
                                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                    End Try

                                                    Response_WriteLine("</p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">ERROR adding new Team <i>" & form_Name & "</i>.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Add Team", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' record already found for this username.  Do not add.
                                                Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE. Cannot add new Team.<br>")
                                                Response_WriteLine("TeamName <i>" & form_Name & "</i> already exists in this location.</font></p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"						

                                form_SiteNum = Me.GetSiteNum(form_LocationIndex)
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<table cellspacing=""0"">")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Team</th></tr>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td><td colspan=""2"">")
                                Response_WriteLine("<b>" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & "</b>")
                                Response_WriteLine("<form name=""frmLinkEditSiteFromAT"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromAT.submit()""><small>Edit</small></a>")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</td></tr>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Location</b>&nbsp;</td>")
                                Response_WriteLine("<td colspan=""2""><b>" & Me.GetLocationName(form_LocationIndex) & "</b>")
                                Response_WriteLine("<form name=""frmLinkEditLocationFromAT"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromAT.submit()""><small>Edit</small></a>")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</td></tr>")
                                tempNames = Me.GetLocationTeamNames(form_LocationIndex, True)
                                If tempNames = "" Then
                                    tempNames = "<font color=""red"">No Teams Exist Yet</font>"
                                Else
                                    tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                End If
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Teams&nbsp;</td><td colspan=""2"">" & tempNames & "</td></tr>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<form name=""form_Method_AddTeam"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddTeam"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                ' LocationIndex passed in as a hidden form value so multiple Teams can be added back-to-back for same Location
                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                sSqlString = "SELECT tab_Teams.Te_SortOrder, tab_Teams.Te_Name, tab_Teams.Te_Active FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & form_LocationIndex & " ORDER BY tab_Teams.Te_SortOrder ASC;"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">First Team will be SortOrder=10.<br>")
                                        Response_WriteLine("This is the order that the new Team will appear in the list of Teams.</td>")
                                    Else
                                        Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                        maxSortOrder = 10
                                        While sqlDataReader.Read = True
                                            If sqlDataReader.Item("Te_SortOrder") > maxSortOrder Then
                                                maxSortOrder = sqlDataReader.Item("Te_SortOrder")
                                            End If
                                            Response_WriteLine("<option value=""AAA" & sqlDataReader.Item("Te_SortOrder") & """>" & sqlDataReader.Item("Te_SortOrder") & " - ")
                                            If sqlDataReader.Item("Te_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & sqlDataReader.Item("Te_Name") & "</option>")
                                        End While
                                        Response_WriteLine("<option value=""ZZZ" & 10 + maxSortOrder & """ selected>" & 10 + maxSortOrder & " - Add to End</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected<br>")
                                        Response_WriteLine("This is the order that the new Team will appear in the list of Teams.</td>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Response_WriteLine("</tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" value="""" size=""50"" maxlength=""255""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">example: PACT Gold Team 1</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td><td><select name=""form_Active"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"">No</option></select></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Team available to receive new Messages<br>")
                                Response_WriteLine("No = Team not available to receive new Messages</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td><td><input type=""text"" name=""form_Notes"" class=""form-control"" value=""New Team " & theDate & """ size=""50"" maxlength=""255""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain Team settings</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Team""></center></td></tr>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p>")
                                Me.ShowTeamsTable(form_LocationIndex)

                            Case "AddMember"

                                If form_Submit = "Choose Selected Account" Then
                                    If ADloop = "x" Then
                                        Response_WriteLine("<p><font color=""red"">Selection cancelled.</font></p>")
                                    Else
                                        If ADloop = "" Then
                                            Response_WriteLine("<p><font color=""red"">Selection submitted but nothing was chosen.</font></p>")
                                        Else
                                            ' name chosen
                                            Response_WriteLine("<p><font color=""green"">Selection complete, auto-filling fields: [Title], Name, Username, SID, Email</font></p>")
                                        End If
                                    End If
                                End If

                                If form_Submit = "Look Up" Then
                                    ' name entered, "Look Up" submitted, load username and email from AD
                                    strADResults = Me.ADNameSearch(form_Name)
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("strADResults=" & strADResults & "<br>")
                                    End If
                                    If strADResults <> "" Then
                                        ' One or more hits found, show the form to pick the right one
                                        ' strFirstname & "_^_" & strLastname & "_^_" & strEmail & "_^_" & strTitle & "_^_" & strFullname & "_^_" & sDomain\strUsername & "_^_" & strSID & "_^__ROW_"
                                        Response_WriteLine("<form name=""frmMethodAddMemberAD"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""ChoseAD"">")
                                        Response_WriteLine("<table>")
                                        Response_WriteLine("<tr><th colspan=""5"" bgcolor=""#d6dbe9"">Choose the closest match or cancel</th></tr>")
                                        strADResults = strADResults & "zzz"

                                        ADrows = Split(strADResults, "_ROW_")
                                        ADloop = 0
                                        Do While ADrows(ADloop) <> "zzz"

                                            ADarray = Split(ADrows(ADloop), "_^_")
                                            If ADarray(0) <> "" Then
                                                ADF = ADarray(0)
                                                If ADarray(1) <> "zzz" Then
                                                    ADL = ADarray(1)
                                                    If ADarray(2) <> "zzz" Then
                                                        ADE = ADarray(2)
                                                        If ADarray(3) <> "zzz" Then
                                                            ADT = ADarray(3)
                                                            If ADarray(4) <> "zzz" Then
                                                                ADFULL = ADarray(4)
                                                                If ADarray(5) <> "zzz" Then
                                                                    ADU = ADarray(5)
                                                                    If ADarray(6) <> "zzz" Then
                                                                        ADSID = ADarray(6)
                                                                    End If
                                                                End If
                                                            End If
                                                        End If
                                                    End If
                                                End If
                                            End If
                                            ' all fields could in theory have a " in them except for the SID
                                            Response_WriteLine("<input type=""hidden"" name=""ADF" & ADloop & """ value=""" & Replace(ADF, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADL" & ADloop & """ value=""" & Replace(ADL, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADE" & ADloop & """ value=""" & Replace(ADE, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADT" & ADloop & """ value=""" & Replace(ADT, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADFULL" & ADloop & """ value=""" & Replace(ADFULL, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADU" & ADloop & """ value=""" & Replace(ADU, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADSID" & ADloop & """ value=""" & ADSID & """>")
                                            If ADloop Mod 2 = 0 Then
                                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                            Else
                                                Response_WriteLine("<tr><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                            End If
                                            ADloop = ADloop + 1
                                        Loop
                                        ' these values were the last of the loop so re-initialize
                                        ADloop = ""
                                        ADF = ""
                                        ADL = ""
                                        ADE = ""
                                        ADT = ""
                                        ADFULL = ""
                                        ADU = ""
                                        ADSID = ""
                                        Response_WriteLine("<tr><td>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADFULLx"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADEx"" value=""" & Replace(form_Email, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADUx"" value=""" & Replace(form_Username, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADSIDx"" value=""" & form_SID & """>")
                                        Response_WriteLine("<input type=""radio"" name=""form_AD"" value=""x""></td>")
                                        Response_WriteLine("<td colspan=""4"">Cancel</td>")
                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("<tr><td colspan=""5""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Choose Selected Account""></center></td></tr>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</form>")
                                    End If

                                Else

                                    OrigUforTable = form_Username

                                    Dim TeamVariable, TeamLoop, TeamArray

                                    ' form_TeamIndex
                                    '   "--- Select multiple ---"
                                    '     "" = cannot exist as Javascript prevents it
                                    '	  ", 15"  = cannot exist as javascript in form submit prevents first item from being selected
                                    '     "15"
                                    '	  "10, 15, 20"
                                    ' strip off situation when user selects "--- Select Multiple ---" and something else
                                    If Left(form_TeamIndex, 2) = ", " Then
                                        form_TeamIndex = Right(form_TeamIndex, Len(form_TeamIndex) - 2)
                                    End If

                                    ' in creation of the Array, add last elemnent "zzz"
                                    TeamArray = Split(form_TeamIndex & ",zzz", ",")

                                    TeamVariable = ""
                                    If form_TeamIndex = "" Then
                                        form_TeamIndex = 0
                                        TeamVariable = "Error"
                                    Else
                                        If Not ContainsComma(form_TeamIndex) Then
                                            ' single Team
                                            TeamVariable = "Single"
                                        Else
                                            If ContainsComma(form_TeamIndex) Then
                                                ' multiple Indexes selected
                                                TeamVariable = "Multiple"
                                            Else
                                                ' not possible!
                                                TeamVariable = "Error"
                                                TeamArray(0) = "Error"
                                            End If
                                        End If
                                    End If

                                    If form_Method = "StoreMe" Then
                                        ' "Add Member" button clicked
                                        ' new AddMember fields submitted, store them

                                        form_Error = ""
                                        If form_SortOrder = "" Then
                                            form_Error = form_Error & " SortOrder"
                                        End If
                                        If form_Name = "" Or form_Name = " " Then
                                            form_Error = form_Error & " Name"
                                        End If
                                        If form_Title = "" Or form_Title = " " Then
                                            form_Error = form_Error & " Title"
                                        End If
                                        If form_Username = "" Then
                                            form_Error = form_Error & " Username"
                                        Else
                                            If InStr(form_Username, "\") Then
                                                ' good, has "\" in the value
                                            Else
                                                ' Missing Valid-Domain\Username
                                                form_Error = form_Error & " Valid-Domain\Username"
                                            End If
                                        End If
                                        If form_SID = "" Then
                                            form_Error = form_Error & " SID"
                                        End If
                                        If form_Email = "" Then
                                            form_Error = form_Error & " Email"
                                        Else
                                            If Not Me.isValidEmail(form_Email) Then
                                                ' Missing Valid-Email
                                                form_Error = form_Error & " Valid-Email"
                                            End If
                                        End If
                                        If form_Notes = "" Then
                                            form_Error = form_Error & " Notes"
                                        End If
                                        If form_Error = "" Then
                                            ' so far is safe to insert

                                            TeamLoop = 0
                                            ' UBound of "3" means array elements [0, 1, 2]
                                            ' "zzz" was added as last element
                                            Do While TeamArray(TeamLoop) <> "zzz" And TeamLoop < UBound(TeamArray)

                                                ' "" value of Array is prevented but check just in case
                                                If TeamArray(TeamLoop) <> "" And TeamArray(TeamLoop) <> "Error" Then
                                                    ' so far is still safe to insert

                                                    ' if username matches, but SID is different, this query would force editing the old person to have the new SID
                                                    sSqlString = "SELECT tab_Members.Me_Index FROM tab_Members WHERE tab_Members.Me_Username LIKE '" & Replace(form_Username, "'", "''") & "' AND tab_Members.Me_TeamIndex = " & TeamArray(TeamLoop) & ";"

                                                    MyCommand.CommandText = sSqlString

                                                    Try
                                                        If MyConnection.State = ConnectionState.Closed Then
                                                            MyConnection.Open()
                                                        End If

                                                        sqlDataReader = MyCommand.ExecuteReader

                                                        If sqlDataReader.Read = False Then
                                                            ' truly is safe, it doesn't exist yet.

                                                            If TeamVariable = "Single" Then
                                                                ' first compute correct sortorder
                                                                ' comes in as: "AAA10, AAA20, AAA30... ZZZ40"
                                                                ' when ZZZ, remove ZZZ and insert as is.
                                                                ' when AAA, shift all existing Members down one.
                                                                If InStr(form_SortOrder, "ZZZ") Then
                                                                    form_SortOrder = Replace(form_SortOrder, "ZZZ", "")
                                                                End If
                                                                If InStr(form_SortOrder, "AAA") Then
                                                                    form_SortOrder = Replace(form_SortOrder, "AAA", "")
                                                                    sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & form_TeamIndex & " AND tab_Members.Me_SortOrder >= " & form_SortOrder & " ORDER BY tab_Members.Me_SortOrder;"
                                                                    If _clsMessageVAR.BDebug = True Then
                                                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                                                    End If

                                                                    MyCommand2.CommandText = sSqlString

                                                                    Try
                                                                        If MyConnection2.State = ConnectionState.Closed Then
                                                                            MyConnection2.Open()
                                                                        End If

                                                                        sqlDataReader2 = MyCommand2.ExecuteReader

                                                                        If Not sqlDataReader2.HasRows Then
                                                                            ' strange, should not get here as the form already guaranteed they would exist
                                                                            Response_WriteLine("<p><font color=""red"">Error computing SortOrder.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                                                        Else
                                                                            While sqlDataReader2.Read = True
                                                                                Response.Write("<br>")
                                                                                UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SortOrder = " & sqlDataReader2.Item("Me_SortOrder") + 10 & " WHERE tab_Members.Me_Index = " & sqlDataReader2.Item("Me_Index") & ";")
                                                                                Response.Write("Member " & sqlDataReader2.Item("Me_Index") & " SortOrder updated from " & sqlDataReader2.Item("Me_SortOrder") & " to " & sqlDataReader2.Item("Me_SortOrder") + 10 & ".<br>")
                                                                            End While
                                                                        End If

                                                                    Catch ex As Exception
                                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                                    Finally
                                                                        If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                                        If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                                    End Try

                                                                End If
                                                            Else
                                                                ' multiple Teams, sort order will be last for each Team
                                                                'Response.Write("TeamLoop=" & TeamLoop & "<br>")
                                                                'Response.Write("TeamArray(TeamLoop)=" & TeamArray(TeamLoop) & "<br>")
                                                                form_SortOrder = Me.GetLastTeamSortOrder(TeamArray(TeamLoop))
                                                                'Response.Write("form_SortOrder=" & form_SortOrder & "<br>")
                                                                form_SortOrder = CInt(form_SortOrder) + 10
                                                            End If

                                                            ' switch to lowercase
                                                            form_Email = LCase(form_Email)
                                                            ' switch to uppercase
                                                            form_Username = UCase(form_Username)

                                                            sSqlString = "INSERT INTO tab_Members (Me_SortOrder, Me_TeamIndex, Me_Name, Me_Title, Me_Username, Me_Email," & " Me_EmailNew, Me_EmailAssign, Me_EmailStatus, Me_ShowOn, Me_Active, Me_SID, Me_Notes)" & " VALUES (" & form_SortOrder & ", " & TeamArray(TeamLoop) & ", '" & Replace(form_Name, "'", "''") & "', '" & Replace(form_Title, "'", "''") & "', '" & Replace(form_Username, "'", "''") & "', '" & Replace(form_Email, "'", "''") & "', '" & form_EmailNew & "', '" & form_EmailAssign & "', '" & form_EmailStatus & "', '" & form_ShowOn & "', '" & form_Active & "', '" & form_SID & "', '" & Replace(form_Notes, "'", "''") & "');"
                                                            If _clsMessageVAR.BDebug = True Then
                                                                Response.Write("sSqlString=" & sSqlString & "<br>")
                                                            End If

                                                            If InsertTableRecord(sSqlString) Then
                                                                ' pass in form_MemberIndex=0 to indicate using Username and TeamIndex as the trigger
                                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                    Response_WriteLine("<p><font color=""green"">New Member <i>" & form_Username & "</i> added successfully to Team <i>" & Me.ColorizeTeamName(Me.GetTeamName(TeamArray(TeamLoop))) & "</i>.</font>")
                                                                Else
                                                                    Response_WriteLine("<p><font color=""green"">New Member <i>" & form_Username & "</i> added successfully to Team <i>" & Me.ColorizeFont(Me.GetTeamName(TeamArray(TeamLoop))) & "</i>.</font>")
                                                                End If
                                                                Response_WriteLine("<form name=""frmLinkEditMemberTI" & TeamArray(TeamLoop) & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditMemberTI" & TeamArray(TeamLoop) & ".submit()""><small>Edit Mmber (to adjust sortorder)</small></a>")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & TeamArray(TeamLoop) & """>")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_MemberIndex"" value=""0"">")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & form_Username & """>")
                                                                Response_WriteLine("</form>")
                                                                Response_WriteLine("</p>")
                                                            Else
                                                                Response_WriteLine("<p><font color=""red"">ERROR adding new Member <i>" & form_Username & "</i>.</font></p>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Add Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                            End If
                                                        Else
                                                            ' record already found for this username.  Do not add.
                                                            Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE USERNAME. Cannot add new Member.<br>")
                                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                Response_WriteLine("Username <i>" & form_Username & "</i> already exists in Team <i>" & Me.ColorizeTeamName(Me.GetTeamName(TeamArray(TeamLoop))) & "</i>.</font>")
                                                            Else
                                                                Response_WriteLine("Username <i>" & form_Username & "</i> already exists in Team <i>" & Me.ColorizeFont(Me.GetTeamName(TeamArray(TeamLoop))) & "</i>.</font>")
                                                            End If
                                                            Response_WriteLine("<form name=""frmLinkEditMemberFailTI" & TeamArray(TeamLoop) & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditMemberFailTI" & TeamArray(TeamLoop) & ".submit()""><small>Edit Member</small></a>")
                                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                                            Response_WriteLine("<input type=""hidden"" name=""form_MemberIndex"" value=""" & sqlDataReader.Item("Me_Index") & """>")
                                                            Response_WriteLine("</form>")
                                                            Response_WriteLine("</p>")
                                                        End If

                                                    Catch ex As Exception
                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                    Finally
                                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                    End Try

                                                Else
                                                    ' not safe to insert, no TeamIndex available!
                                                    Response_WriteLine("<p><font color=""red"">Error - Missing Team. Start the Edit Setup option over again.</font></p>")
                                                End If

                                                TeamLoop = TeamLoop + 1
                                            Loop

                                        Else
                                            ' missing info, try again
                                            Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                        End If
                                        ' if storing name, wipe the fields so can submit another person into same fields
                                        form_Name = ""
                                        form_Username = ""
                                        form_Email = ""
                                        form_SID = ""

                                    End If ' form_Method = "StoreMe"

                                    ' SHOW Add Member form '
                                    ' show this form no matter which phase of AD lookup

                                    ' either first time in, or name chosen/cancelled from AD
                                    If form_Method = "ChoseAD" Then
                                        ' ADFULL not used, regenerate without middle initial and in "First Last" form
                                        If ADloop = "x" Or ADloop = "" Then
                                            ' x means cancel clicked, use the previously typed in value still
                                            ADFULL = Request.Form("ADFULLx")
                                            ADE = Request.Form("ADEx")
                                            ' ADT not passed through in form
                                            ADU = Request.Form("ADUx")
                                            ADSID = Request.Form("ADSIDx")
                                        Else
                                            ' AD form used, name selected, load First, Last, Email, Title, SID
                                            ADF = Request.Form("ADF" & ADloop)
                                            ADL = Request.Form("ADL" & ADloop)
                                            ADE = Request.Form("ADE" & ADloop)
                                            ' Title shown for reference here, not used in form field though
                                            ADT = Request.Form("ADT" & ADloop)
                                            ADU = Request.Form("ADU" & ADloop)
                                            ADSID = Request.Form("ADSID" & ADloop)

                                            ' ADFULL not used from display name.  generate instead
                                            ' use "first last" notation
                                            ' ADFULL = Request.Form("ADFULL" & ADloop)
                                            ADFULL = ADF & " " & ADL
                                        End If
                                    Else
                                        ' first time into form, no fields loaded yet
                                        ADFULL = ""
                                        ADSID = ""
                                        ADE = ""
                                        ADU = ""
                                        ADT = ""
                                    End If
                                    ADU = UCase(ADU)
                                    ADE = LCase(ADE)
                                    ADT = Replace(ADT, "EXEMPT: ", "")
                                    Response_WriteLine("<p>")
                                    Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                    Response_WriteLine("<table cellspacing=""0"">")
                                    Select Case TeamVariable
                                        Case "Single"
                                            form_SiteNum = Me.GetSiteNum(Me.GetLocationIndex(TeamArray(0)))
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Member to Single Team</th></tr>")
                                            Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td><td colspan=""2"">")
                                            Response_WriteLine("<b>" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & "</b>")
                                            Response_WriteLine("<form name=""frmLinkEditSiteFromAMS"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromAMS.submit()""><small>Edit</small></a>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Location</b>&nbsp;</td>")
                                            Response_WriteLine("<td colspan=""2""><b>" & Me.GetLocationName(Me.GetLocationIndex(TeamArray(0))) & "</b>")
                                            Response_WriteLine("<form name=""frmLinkEditLocationFromAMS"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromAMS.submit()""><small>Edit</small></a>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & Me.GetLocationIndex(TeamArray(0)) & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Team</b>&nbsp;</td>")
                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                Response_WriteLine("<td colspan=""2""><b>" & Me.ColorizeTeamName(Me.GetTeamName(TeamArray(0))) & "</b>")
                                            Else
                                                Response_WriteLine("<td colspan=""2""><b>" & Me.ColorizeFont(Me.GetTeamName(TeamArray(0))) & "</b>")
                                            End If
                                            Response_WriteLine("<form name=""frmLinkEditTeamSinI" & TeamArray(0) & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditTeamSinI" & TeamArray(0) & ".submit()"">Edit</a>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & TeamArray(0) & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</td></tr>")
                                            ' check for Nothing list
                                            tempNames = Me.GetTeamMemberNames(form_TeamIndex, True, True)
                                            If tempNames = "" Then
                                                tempNames = "<font color=""red"">No Members Exist Yet</font>"
                                            Else
                                                tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                            End If
                                            Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Team&nbsp;Members&nbsp;</td>")
                                            Response_WriteLine("<td colspan=""2"">" & tempNames & "</td></tr>")
                                            ' check for Nothing list
                                            tempEmail = Me.GetTeamMemberNewEmails(form_TeamIndex)
                                            If tempEmail = "" Then
                                                tempEmail = "<font color=""red"">No Email Recipients for New Messages</font>"
                                            Else
                                                tempEmail = LCase(tempEmail)
                                            End If
                                            Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">New&nbsp;Message&nbsp;Emails&nbsp;</td>")
                                            Response_WriteLine("<td colspan=""2"">" & tempEmail & "</td></tr>")
                                        Case "Multiple"
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Member to Multiple Teams</th></tr>")
                                            Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site,&nbsp;Location,&nbsp;Team</b>&nbsp;</td>")
                                            Response_WriteLine("<td colspan=""2"">")
                                            TeamLoop = 0
                                            Do While TeamArray(TeamLoop) <> "zzz"
                                                form_SiteNum = Me.GetSiteNum(Me.GetLocationIndex(TeamArray(TeamLoop)))
                                                Response_WriteLine("<b>")
                                                Response_WriteLine("" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & ", ")
                                                Response_WriteLine("" & Me.GetLocationName(Me.GetLocationIndex(TeamArray(TeamLoop))) & ", ")
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine("" & Me.ColorizeTeamName(Me.GetTeamName(TeamArray(TeamLoop))) & "")
                                                Else
                                                    Response_WriteLine("" & Me.ColorizeFont(Me.GetTeamName(TeamArray(TeamLoop))) & "")
                                                End If
                                                Response_WriteLine("</b>")
                                                Response_WriteLine("<form name=""frmLinkEditTeamMulI" & TeamArray(TeamLoop) & """ action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditTeamMulI" & TeamArray(TeamLoop) & ".submit()""><small>Edit</small></a>")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & TeamArray(TeamLoop) & """>")
                                                Response_WriteLine("</form>")
                                                Response_WriteLine("<br>")
                                                TeamLoop = TeamLoop + 1
                                            Loop
                                            Response_WriteLine("</td></tr>")
                                    End Select

                                    ' show the form header between the top half and the sort order
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                    Response_WriteLine("<form name=""frmMethodAddMember"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                    ' TeamIndex is passed in as a hidden form value so multiple members can be added back-to-back for same Team(s)
                                    Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                    Select Case TeamVariable
                                        Case "Single"
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                            sSqlString = "SELECT tab_Members.Me_SortOrder, tab_Members.Me_Name, tab_Members.Me_Active" & " FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & form_TeamIndex & " ORDER BY tab_Members.Me_SortOrder ASC;"
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("sSqlString=" & sSqlString & "<br>")
                                            End If

                                            MyCommand.CommandText = sSqlString

                                            Try
                                                If MyConnection.State = ConnectionState.Closed Then
                                                    MyConnection.Open()
                                                End If

                                                sqlDataReader = MyCommand.ExecuteReader

                                                If Not sqlDataReader.HasRows Then
                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">First Member will be SortOrder=10.<br>")
                                                    Response_WriteLine("This is the order that the new Member will appear in the list of Members.</td>")
                                                Else
                                                    Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                                    maxSortOrder = 10
                                                    While sqlDataReader.Read = True
                                                        If sqlDataReader.Item("Me_SortOrder") > maxSortOrder Then
                                                            maxSortOrder = sqlDataReader.Item("Me_SortOrder")
                                                        End If
                                                        Response_WriteLine("<option value=""AAA" & sqlDataReader.Item("Me_SortOrder") & """>" & sqlDataReader.Item("Me_SortOrder") & " - ")
                                                        If sqlDataReader.Item("Me_Active") = "No" Then
                                                            Response_WriteLine("* ")
                                                        End If
                                                        Response_WriteLine("" & sqlDataReader.Item("Me_Name") & "</option>")
                                                    End While
                                                    Response_WriteLine("<option value=""ZZZ" & 10 + maxSortOrder & """ selected>" & 10 + maxSortOrder & " - Add to End</option>")
                                                    Response_WriteLine("</select></td>")
                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected.<br>")
                                                    Response_WriteLine("This is the order that the new Member will appear in the list of Members.<br>")
                                                    Response_WriteLine("Organize the Team Members in this style:<br>")
                                                    Response_WriteLine("MD first, NP, PA, RN, LPN, MSA</td>")
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                            Response_WriteLine("</tr>")
                                        Case "Multiple"
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                            Response_WriteLine("<td>Last<input type=""hidden"" name=""form_SortOrder"" value=""ZZZ""></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">After Submitting, adjust SortOrder in the Edit Member menu item.<br>")
                                            Response_WriteLine("Organize the Team Members in this style:<br>")
                                            Response_WriteLine("MD first, NP, PA, RN, LPN, MSA</td>")
                                            Response_WriteLine("</tr>")
                                        Case Else
                                            ' "Error"
                                            Response_WriteLine("<p><font color=""red"">ERROR - Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End Select


                                    If TeamVariable <> "Error" Then
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Title&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Title"" class=""form-control""><option></option>")
                                        sSqlString = "SELECT tab_Titles.Ti_Title, tab_Titles.Ti_Description FROM tab_Titles ORDER BY Ti_SortOrder;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.HasRows Then
                                                ' none found
                                            Else
                                                While sqlDataReader.Read = True
                                                    If ADT <> "" Then
                                                        Response_WriteLine("" & Me.CreateTitleOption(ADT, sqlDataReader.Item("Ti_Title"), sqlDataReader.Item("Ti_Description")) & "")
                                                    Else
                                                        Response_WriteLine("<option value=""" & Replace(sqlDataReader.Item("Ti_Title"), """", "&#34;") & """>" & sqlDataReader.Item("Ti_Title") & "")
                                                        If Not IsDBNull(sqlDataReader.Item("Ti_Description")) Then
                                                            Response_WriteLine("- " & sqlDataReader.Item("Ti_Description") & "")
                                                        End If
                                                        Response_WriteLine("</option>")
                                                    End If
                                                End While
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Choose Title from the list.")
                                        If ADT <> "" Then
                                            Response_WriteLine("&nbsp;(" & ADT & ")")
                                        End If
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top"" bgcolor=""#d6dbe9""><td align=""right"">Name&nbsp;</td>")
                                        Response_WriteLine("<td><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(ADFULL, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                        Response_WriteLine("<td>1. Enter full or partial name in form of ""Last, First"" or ""First Last""<br>")
                                        Response_WriteLine("2. Click <input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Look Up""> to search in Active Directory.<br>")
                                        Response_WriteLine("3. Username and Email address will be retrieved.<br>")
                                        Response_WriteLine("(If you are unable to pull up a name, enter ""VA\"" before the last name, first name to search all va.gov Domain)")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Username&nbsp;</td>")
                                        Response_WriteLine("<td>" & ADU & "")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & Replace(ADU, """", "&#34;") & """></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding Username.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">SID&nbsp;</td><td>")
                                        Response_WriteLine("<small><i>" & "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & "</i></small>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SID"" value=""" & ADSID & """></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding SID.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Email&nbsp;</td>")
                                        Response_WriteLine("<td><input type=""text"" name=""form_Email"" class=""form-control"" value=""" & Replace(ADE, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">example: first.last@va.gov</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">EmailNew&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_EmailNew"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"" selected>No</option></select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">If Yes, member receives email for new and transferred messages.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">EmailAssign&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_EmailAssign"" class=""form-control""><option value=""Yes"" selected>Yes</option><option value=""No"">No</option></select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">If Yes, member receives email when the message is assigned to this member.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">EmailStatus&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_EmailStatus"" class=""form-control""><option value=""No"" selected>No</option></select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Add/Edit Member - Functionality disabled for current implementation.<br>")
                                        Response_WriteLine("* Note - Members previously setup 'Yes' will continue email status until manual adjustment.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">ShowOn&nbsp;</td><td><select name=""form_ShowOn"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"">No</option></select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Is Member name shown appended to the Team name on the Team Selection section of a New Message?<br>")
                                        Response_WriteLine("Yes = Displays the Member name<br>")
                                        Response_WriteLine("No = Does not display the Member name")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Active"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"">No</option></select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Member can be assigned Messages.<br>")
                                        Response_WriteLine("No = Member still part of team but cannot be assigned Messages.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td>")
                                        Response_WriteLine("<td><input type=""text"" name=""form_Notes"" class=""form-control"" value=""New team member " & theDate & """ size=""40"" maxlength=""255""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain Member settings</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Member""></center></td></tr>")
                                    End If ' TeamVariable <> "Error"
                                    Response_WriteLine("</form>")
                                    Response_WriteLine("</table>")
                                    Response_WriteLine("</td></tr></table>")
                                    Response_WriteLine("</p>")
                                    ' can show Members table for 000 admins because it will default to this team's site
                                    If TeamVariable = "Single" Then
                                        Me.ShowMembersTable(form_TeamIndex, OrigUforTable)
                                        Me.ShowTeamsTable(Me.GetLocationIndex(form_TeamIndex))
                                    Else
                                        Me.ShowMembersTable(0, OrigUforTable)
                                        Me.ShowTeamsTable(Me.GetLocationIndex(TeamArray(0)))
                                    End If
                                End If  ' form_Submit = "Look Up"

                            Case "AddAdmin"

                                If form_Submit = "Choose Selected Account" Then
                                    If ADloop = "x" Then
                                        Response_WriteLine("<p><font color=""red"">Selection cancelled.</font></p>")
                                    Else
                                        If ADloop = "" Then
                                            Response_WriteLine("<p><font color=""red"">Selection submitted but nothing was chosen.</font></p>")
                                        Else
                                            ' name chosen
                                            Response_WriteLine("<p><font color=""green"">Selection complete, auto-filling fields: Name, Username, SID, Email</font></p>")
                                        End If
                                    End If
                                End If

                                If form_Submit = "Look Up" Then
                                    ' name entered, "Look Up" submitted, load username and email from AD
                                    strADResults = Me.ADNameSearch(form_Name)
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("strADResults=" & strADResults & "<br>")
                                    End If
                                    If strADResults <> "" Then
                                        ' One or more hits found, show the form to pick the right one
                                        ' strFirstname & "_^_" & strLastname & "_^_" & strEmail & "_^_" & strTitle & "_^_" & strFullname & "_^_" & sDomain\strUsername & "_^_" & strSID & "_^__ROW_"
                                        Response_WriteLine("<form name=""frmMethodAddAdminAD"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Name"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddAdmin"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""ChoseAD"">")
                                        Response_WriteLine("<table>")
                                        Response_WriteLine("<tr><th colspan=""5"" bgcolor=""#d6dbe9"">Choose the closest match or cancel</th></tr>")
                                        strADResults = strADResults & "zzz"

                                        ADrows = Split(strADResults, "_ROW_")
                                        ADloop = 0
                                        Do While ADrows(ADloop) <> "zzz"

                                            ADarray = Split(ADrows(ADloop), "_^_")
                                            If ADarray(0) <> "" Then
                                                ADF = ADarray(0)
                                                If ADarray(1) <> "zzz" Then
                                                    ADL = ADarray(1)
                                                    If ADarray(2) <> "zzz" Then
                                                        ADE = ADarray(2)
                                                        If ADarray(3) <> "zzz" Then
                                                            ADT = ADarray(3)
                                                            If ADarray(4) <> "zzz" Then
                                                                ADFULL = ADarray(4)
                                                                If ADarray(5) <> "zzz" Then
                                                                    ADU = ADarray(5)
                                                                    If ADarray(6) <> "zzz" Then
                                                                        ADSID = ADarray(6)
                                                                    End If
                                                                End If
                                                            End If
                                                        End If
                                                    End If
                                                End If
                                            End If
                                            ' all fields could in theory have a " in them except for the SID
                                            Response_WriteLine("<input type=""hidden"" name=""ADF" & ADloop & """ value=""" & Replace(ADF, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADL" & ADloop & """ value=""" & Replace(ADL, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADE" & ADloop & """ value=""" & Replace(ADE, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADT" & ADloop & """ value=""" & Replace(ADT, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADFULL" & ADloop & """ value=""" & Replace(ADFULL, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADU" & ADloop & """ value=""" & Replace(ADU, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADSID" & ADloop & """ value=""" & ADSID & """>")
                                            If ADloop Mod 2 = 0 Then
                                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                            Else
                                                Response_WriteLine("<tr><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                            End If
                                            ADloop = ADloop + 1
                                        Loop
                                        ' these values were the last of the loop so re-initialize
                                        ADloop = ""
                                        ADF = ""
                                        ADL = ""
                                        ADE = ""
                                        ADT = ""
                                        ADFULL = ""
                                        ADU = ""
                                        ADSID = ""
                                        Response_WriteLine("<tr><td>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADFULLx"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADEx"" value=""" & Replace(form_Email, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADUx"" value=""" & Replace(form_Username, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADSIDx"" value=""" & form_SID & """>")
                                        Response_WriteLine("<input type=""radio"" name=""form_AD"" value=""x""></td>")
                                        Response_WriteLine("<td colspan=""4"">Cancel</td>")
                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("<tr><td colspan=""5""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Choose Selected Account""></center></td></tr>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</form>")
                                    End If

                                Else

                                    OrigUforTable = form_Username

                                    If form_Method = "StoreMe" Then
                                        ' new AddAdmin fields submitted, store them
                                        ' all fields required

                                        form_Error = ""
                                        If form_Username = "" Then
                                            form_Error = form_Error & " Username"
                                        Else
                                            If InStr(form_Username, "\") Then
                                                ' good, has "\" in the value
                                            Else
                                                ' Missing Valid-Domain\Username
                                                form_Error = form_Error & " Valid-Domain\Username"
                                            End If
                                        End If
                                        If form_SID = "" Then
                                            form_Error = form_Error & " SID"
                                        End If
                                        If form_SiteNum = "" Then
                                            form_Error = form_Error & " SiteNum"
                                        End If
                                        If form_Access = "" Then
                                            form_Error = form_Error & " Access"
                                        End If
                                        If form_Type = "" Then
                                            form_Error = form_Error & " Type"
                                        Else
                                            If form_Type = "None Found" Then
                                                form_Error = form_Error & " Type(create-Types-first)"
                                            End If
                                        End If
                                        If form_Name = "" Then
                                            form_Error = form_Error & " Name"
                                        End If
                                        If form_Email = "" Then
                                            form_Error = form_Error & " Email"
                                        Else
                                            ' not Nothing, ensure valid
                                            If Not Me.isValidEmail(form_Email) Then
                                                ' Missing Valid-Email
                                                form_Error = form_Error & " Valid-Email"
                                            End If
                                        End If
                                        ' form_FlagOn guaranteed to be "Yes" or "No"
                                        If form_Notes = "" Then
                                            form_Error = form_Error & " Notes"
                                        End If
                                        If form_SiteNum = "000" And form_Sites = "" Then
                                            form_Error = form_Error & " Must Select at least one Site below for SiteNum 000"
                                        End If
                                        If form_Error = "" Then
                                            ' safe to insert

                                            ' if username matches, but SID is different, this query would force editing the old person to have the new SID
                                            sSqlString = "SELECT * FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';"

                                            MyCommand.CommandText = sSqlString

                                            Try
                                                If MyConnection.State = ConnectionState.Closed Then
                                                    MyConnection.Open()
                                                End If

                                                sqlDataReader = MyCommand.ExecuteReader

                                                If Not sqlDataReader.HasRows Then
                                                    ' truly is safe, it doesn't exist yet.

                                                    ' switch to uppercase
                                                    form_Username = UCase(form_Username)
                                                    ' first convert to Lowercase
                                                    form_Email = LCase(form_Email)

                                                    sSqlString = "INSERT INTO tab_Admins (Adm_Username, Adm_SiteNum, Adm_AccessLevel, Adm_Type, Adm_Name, Adm_Email, Adm_FlagOn, Adm_SID, Adm_Notes, Adm_Sites) " & "VALUES ('" & Replace(form_Username, "'", "''") & "', '" & Replace(form_SiteNum, "'", "''") & "', '" & Replace(form_Access, "'", "''") & "', '" & Replace(form_Type, "'", "''") & "', '" & Replace(form_Name, "'", "''") & "', '" & Replace(form_Email, "'", "''") & "', '" & form_FlagOn & "', '" & form_SID & "', '" & Replace(form_Notes, "'", "''") & "', '" & Replace(form_Sites, "'", "''") & "' );"
                                                    If _clsMessageVAR.BDebug = True Then
                                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                                    End If

                                                    If InsertTableRecord(sSqlString) Then
                                                        Response_WriteLine("<p><font color=""green"">New Admin <i>" & form_Username & "</i> added successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR adding new Admin <i>" & form_Username & "</i>.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Add Admin", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' record already found for this username.  Do not add.
                                                    Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE USERNAME. Cannot add new Admin.<br>")
                                                    Response_WriteLine("Username <i>" & form_Username & "</i> already exists.</font></p>")
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                        Else
                                            ' missing info, try again
                                            Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                        End If
                                        ' clear out name fields so can add another
                                        form_Username = ""
                                        form_Email = ""
                                        form_Name = ""
                                        form_SID = ""

                                    End If  ' form_Method = "StoreMe"

                                    ' SHOW Add Admin form '

                                    ' either first time in, or name chosen/cancelled from AD
                                    If form_Method = "ChoseAD" Then
                                        ' title not used with Admin
                                        ' ADFULL not used, regenerate without middle initial and in "First Last" form
                                        If ADloop = "x" Or ADloop = "" Then
                                            ' x means cancel clicked, use the previously typed in value still
                                            ADFULL = Request.Form("ADFULLx")
                                            ADE = Request.Form("ADEx")
                                            ADU = Request.Form("ADUx")
                                            ADSID = Request.Form("ADSIDx")
                                        Else
                                            ' AD form used, name selected, load First, Last and Email
                                            ADF = Request.Form("ADF" & ADloop)
                                            ADL = Request.Form("ADL" & ADloop)
                                            ADE = Request.Form("ADE" & ADloop)
                                            ' Title not used with Admin
                                            ' ADT = Request.Form("ADT" & ADloop)
                                            ADU = Request.Form("ADU" & ADloop)
                                            ADSID = Request.Form("ADSID" & ADloop)

                                            ' ADFULL not used from display name.  generate instead
                                            ' use "first last" notation
                                            ' ADFULL = Request.Form("ADFULL" & ADloop)
                                            ADFULL = ADF & " " & ADL
                                        End If
                                    Else
                                        ' first time into AD search, no fields loaded yet
                                        ADFULL = ""
                                        ADSID = ""
                                        ADE = ""
                                        ADU = ""
                                        ' Title not used with Admin
                                        ' ADT = ""
                                    End If
                                    ADU = UCase(ADU)
                                    ADE = LCase(ADE)
                                    Response_WriteLine("<p>")
                                    Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                    Response_WriteLine("<Table cellspacing=""0"">")
                                    Response_WriteLine("<form name=""form_Method_AddAdmin"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddAdmin"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                    Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add an Admin</th></tr>")
                                    'Response_WriteLine("<tr><td bgcolor=""#dbe4f0"" colspan=""3""><hr color=""black""></td></tr>")
                                    Response_WriteLine("<tr valign=""top"" bgcolor=""#d6dbe9""><td align=""right"">Name&nbsp;</td>")
                                    Response_WriteLine("<td><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(ADFULL, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                    Response_WriteLine("<td>1. Enter full or partial name in form of ""Last, First"" or ""First Last""<br>")
                                    Response_WriteLine("2. Click <input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Look Up""> to search in Active Directory.<br>")
                                    Response_WriteLine("3. Username and Email address will be retrieved.<br>")
                                    Response_WriteLine("(If you are unable to pull up a name, enter ""VA\"" before the last name, first name to search all va.gov Domain)")
                                    Response_WriteLine("</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Username&nbsp;</td>")
                                    Response_WriteLine("<td>" & ADU & "")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & Replace(ADU, """", "&#34;") & """></td>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Sites"" id=""ID_Sites"" value=""""></td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding Username.</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">SID&nbsp;</td>")
                                    Response_WriteLine("<td><small><i>" & "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & "</i></small>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_SID"" value=""" & ADSID & """></td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding SID.</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Email&nbsp;</td>")
                                    Response_WriteLine("<td><input type=""text"" name=""form_Email"" class=""form-control"" value=""" & Replace(ADE, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">example: first.last@va.gov<br>")
                                    Response_WriteLine("</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum&nbsp;</td><td>")
                                    Response_WriteLine("<select name=""form_SiteNum"" id=""ID_Select"" class=""form-control"">")
                                    Response_WriteLine("<option></option>")
                                    sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                    If Me.AdminSite = "000" Then
                                        ' don't limit by S, meaning show all sites assigned
                                        sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum IN(" & Me.AdminSites & ",'000')"
                                    Else
                                        ' limit by chosen S
                                        sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                    End If
                                    sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If Not sqlDataReader.HasRows Then
                                            ' none found
                                        Else
                                            While sqlDataReader.Read = True
                                                Response_WriteLine("<option value=""" & sqlDataReader.Item("Si_SiteNum") & """>" & sqlDataReader.Item("Si_SiteNum") & " - ")
                                                If sqlDataReader.Item("Si_Active") = "No" Then
                                                    Response_WriteLine("* ")
                                                End If
                                                Response_WriteLine("" & Replace(sqlDataReader.Item("Si_Name"), "Choose Site", "") & "</option>")
                                            End While
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    Response_WriteLine("</select>")
                                    Response_WriteLine("</td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">000 = Selected Sites (checked below)<br>")
                                    Response_WriteLine("Or pick a Site Number to limit Access to that site</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Access&nbsp;</td>")
                                    Response_WriteLine("<td><select name=""form_Access"" class=""form-control""><option selected></option>")
                                    Response_WriteLine("<option value=""Admin"">Admin</option>")
                                    Response_WriteLine("<option value=""Site"">Site</option>")
                                    Response_WriteLine("</select></td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Admin = Can View and Edit all Messages.  Can Edit Setup.<br>")
                                    Response_WriteLine("Site = Can View and Edit all Messages.  Cannot View or Edit Setup.")
                                    Response_WriteLine("</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type&nbsp;</td>")
                                    Response_WriteLine("<td><select name=""form_Type"" class=""form-control"">")
                                    optionCount = 0
                                    optionItem = ""
                                    sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons"
                                    If Me.AdminType = "All" Then
                                        ' don't limit by Type, meaning show all types
                                    Else
                                        ' limit by Type
                                        sSqlString = sSqlString & " WHERE tab_Reasons.Re_Type = '" & Me.AdminType & "'"
                                    End If
                                    sSqlString = sSqlString & " ORDER BY tab_Reasons.Re_Type;"

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If Not sqlDataReader.HasRows Then
                                            optionCount = 0
                                            optionItem = "<option value=""None Found"">None Found</option>" & vbCrLf
                                        Else
                                            While sqlDataReader.Read = True
                                                ' Exclude FEE and PACT as per John P. TJD
                                                If sqlDataReader.Item("REASONTYPE") <> "FEE" And sqlDataReader.Item("REASONTYPE") <> "PACT" Then
                                                    optionItem = optionItem & "<option value=""" & sqlDataReader.Item("REASONTYPE") & """>" & sqlDataReader.Item("REASONTYPE") & "</option>" & vbCrLf
                                                    optionCount = optionCount + 1
                                                End If
                                            End While
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    ' insert "All" at the top
                                    optionItem = "<option value=""All"">All</option>" & optionItem & vbCrLf
                                    optionCount = optionCount + 1

                                    If optionCount > 1 Then
                                        ' default a blank at the top so a type has to be chosen
                                        optionItem = "<option></option>" & optionItem & vbCrLf
                                    Else
                                        ' insert no blank at the top
                                    End If
                                    Response.Write(optionItem)
                                    Response_WriteLine("</select></td>						")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Choose the Type of Teams that this admin will manage</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">FlagOn&nbsp;</td>")
                                    Response_WriteLine("<td><select name=""form_FlagOn"" class=""form-control""><option value=""Yes"">Yes</option><option value=""No"" selected>No</option></select></td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Used for ""Message Escalation"" recipient when these are all true:<br>")
                                    Response_WriteLine("- FlagOn  to ""Yes""<br>")
                                    Response_WriteLine("- all Locations under this SiteNum<br>")
                                    Response_WriteLine("- when the Admin's SiteNum is ""000"" or matches the Site<br>")
                                    Response_WriteLine("- when the Admin's Type is ""All"" or matches the Location's Type")
                                    Response_WriteLine("</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                    Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td>")
                                    Response_WriteLine("<td><input type=""text"" name=""form_Notes"" class=""form-control"" value=""Access added " & theDate & """ size=""40"" maxlength=""255""></td>")
                                    Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain Admin privileges</td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                    Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Admin""></center></td></tr>")
                                    Response_WriteLine("</form>")
                                    Response_WriteLine("</Table>")
                                    Response_WriteLine("</td></tr></table>")
                                    Response_WriteLine("</p>")
                                    sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                    If Me.AdminSite = "000" Then
                                        sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum <> '000'"
                                    Else
                                        ' limit by chosen S
                                        sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                    End If
                                    sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString
                                    Response_WriteLine("<p><div class=""000 box"" style=""width:50%;border:1px solid #58589d;background-color: #fff;""><strong style=""color: #ff0000;"">Selected Sites for SiteNum 000:</strong>")
                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If Not sqlDataReader.HasRows Then
                                            ' none found
                                        Else
                                            Response_WriteLine("<fieldset>")
                                            While sqlDataReader.Read = True
                                                If Me.AdminSites.ToString.Contains("'" & sqlDataReader.Item("Si_SiteNum") & "'") Then
                                                    Response_WriteLine("<input type=""checkbox"" checked id=""" & "'" & sqlDataReader.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader.Item("Si_SiteNum") & " - ")
                                                Else
                                                    Response_WriteLine("<input type=""checkbox"" id=""" & "'" & sqlDataReader.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader.Item("Si_SiteNum") & " - ")
                                                End If
                                                If sqlDataReader.Item("Si_Active") = "No" Then
                                                    Response_WriteLine("* ")
                                                End If
                                                Response_WriteLine("" & Replace(sqlDataReader.Item("Si_Name"), "Choose Site", "") & "</input><br/>")
                                            End While
                                            Response_WriteLine("</fieldset>")
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try
                                    Response_WriteLine("</div></p>")
                                    Me.ShowAdminsTable(OrigUforTable)

                                End If  ' form_Submit = "Look Up"

                            Case "AddADGroup"

                                If form_Method = "StoreMe" Then
                                    ' new AddADGroup fields submitted, store them

                                    form_Error = ""
                                    If form_SiteNum = "" Then
                                        form_Error = form_Error & " SiteNum"
                                    End If
                                    If form_Access = "" Then
                                        form_Error = form_Error & " Access"
                                    End If
                                    If form_Type = "" Then
                                        form_Error = form_Error & " Type"
                                    Else
                                        If form_Type = "None Found" Then
                                            form_Error = form_Error & " Type(create-Types-first)"
                                        End If
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " AD Group Name"
                                    End If
                                    If form_SiteNum = "000" And form_Sites = "" Then
                                        form_Error = form_Error & " Must Select at least one Site below for SiteNum 000"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to insert

                                        sSqlString = "SELECT * FROM tab_ADGroups WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.HasRows Then
                                                ' truly is safe, it doesn't exist yet.
                                                If ADGroupExists(form_Name) Then
                                                    sSqlString = "INSERT INTO tab_ADGroups (AD_SiteNum, AD_AccessLevel, AD_Type, AD_GroupName, AD_Sites) " & "VALUES ('" & Replace(form_SiteNum, "'", "''") & "', '" & Replace(form_Access, "'", "''") & "', '" & Replace(form_Type, "'", "''") & "', '" & Replace(form_Name, "'", "''") & "', '" & Replace(form_Sites, "'", "''") & "');"
                                                    If _clsMessageVAR.BDebug = True Then
                                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                                    End If

                                                    If InsertTableRecord(sSqlString) Then
                                                        Response_WriteLine("<p><font color=""green"">New AD Group <i>" & form_Name & "</i> added successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR adding new AD Group <i>" & form_Name & "</i>.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Add ADGroup", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">ERROR NOT FOUND. Cannot add new AD Group Name.<br>")
                                                    Response_WriteLine("AD Group Name <i>" & form_Name & "</i> not found in Active Directory!</font></p>")
                                                End If
                                            Else
                                                ' record already found for this AD Group.  Do not add.
                                                Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE. Cannot add new AD Group Name.<br>")
                                                Response_WriteLine("AD Group Name <i>" & form_Name & "</i> already exists.</font></p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<Table cellspacing=""0"">")
                                Response_WriteLine("<form name=""form_Method_AddADGroup"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddADGroup"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Sites"" id=""ID_Sites"" value=""""></td>")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add an AD Group</th></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum&nbsp;</td><td>")
                                Response_WriteLine("<select name=""form_SiteNum"" id=""ID_Select"" class=""form-control"">")
                                Response_WriteLine("<option></option>")
                                sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                If Me.AdminSite = "000" Then
                                    ' don't limit by S, meaning show all sites assigned
                                    sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum IN(" & Me.AdminSites & ",'000')"
                                Else
                                    ' limit by chosen S
                                    sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        ' none found
                                    Else
                                        While sqlDataReader.Read = True
                                            Response_WriteLine("<option value=""" & sqlDataReader.Item("Si_SiteNum") & """>" & sqlDataReader.Item("Si_SiteNum") & " - ")
                                            If sqlDataReader.Item("Si_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & Replace(sqlDataReader.Item("Si_Name"), "Choose Site", "") & "</option>")
                                        End While
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Response_WriteLine("</select>")
                                Response_WriteLine("</td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">000 = Selected Sites (checked below)<br>")
                                Response_WriteLine("Or pick a Site Number to limit Access to that site</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Access&nbsp;</td>")
                                Response_WriteLine("<td><select name=""form_Access"" class=""form-control""><option selected></option>")
                                Response_WriteLine("<option value=""Admin"">Admin</option>")
                                Response_WriteLine("<option value=""Site"">Site</option>")
                                Response_WriteLine("</select></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Admin = Can View and Edit all Messages.  Can Edit Setup.<br>")
                                Response_WriteLine("Site = Can View and Edit all Messages.  Cannot View or Edit Setup.")
                                Response_WriteLine("</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type&nbsp;</td>")
                                Response_WriteLine("<td><select name=""form_Type"" class=""form-control"">")
                                optionCount = 0
                                optionItem = ""
                                sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons"
                                If Me.AdminType = "All" Then
                                    ' don't limit by Type, meaning show all types
                                Else
                                    ' limit by Type
                                    sSqlString = sSqlString & " WHERE tab_Reasons.Re_Type = '" & Me.AdminType & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Reasons.Re_Type;"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        optionCount = 0
                                        optionItem = "<option value=""None Found"">None Found</option>" & vbCrLf
                                    Else
                                        While sqlDataReader.Read = True
                                            ' Exclude FEE and PACT as per John P. TJD
                                            If sqlDataReader.Item("REASONTYPE") <> "FEE" And sqlDataReader.Item("REASONTYPE") <> "PACT" Then
                                                optionItem = optionItem & "<option value=""" & sqlDataReader.Item("REASONTYPE") & """>" & sqlDataReader.Item("REASONTYPE") & "</option>" & vbCrLf
                                                optionCount = optionCount + 1
                                            End If
                                        End While
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                ' insert "All" at the top
                                optionItem = "<option value=""All"">All</option>" & optionItem & vbCrLf
                                optionCount = optionCount + 1

                                If optionCount > 1 Then
                                    ' default a blank at the top so a type has to be chosen
                                    optionItem = "<option></option>" & optionItem & vbCrLf
                                Else
                                    ' insert no blank at the top
                                End If
                                Response.Write(optionItem)
                                Response_WriteLine("</select></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Choose the Type of Teams that this group will manage</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">AD Group Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" value="""" size=""40"" maxlenght=""255""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Active Directory Distribution List name.<br>")
                                Response_WriteLine("It allows an Owner to manage the membership.</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add AD Group""></center></td></tr>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</Table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p>")
                                sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                If Me.AdminSite = "000" Then
                                    sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum <> '000'"
                                Else
                                    ' limit by chosen S
                                    sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                End If
                                sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString
                                Response_WriteLine("<p><div class=""000 box"" style=""width:50%;border:1px solid #58589d;background-color: #fff;""><strong style=""color: #ff0000;"">Selected Sites for SiteNum 000:</strong>")
                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        ' none found
                                    Else
                                        Response_WriteLine("<fieldset>")
                                        While sqlDataReader.Read = True
                                            If Me.AdminSites.ToString.Contains("'" & sqlDataReader.Item("Si_SiteNum") & "'") Then
                                                Response_WriteLine("<input type=""checkbox"" checked id=""" & "'" & sqlDataReader.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader.Item("Si_SiteNum") & " - ")
                                            Else
                                                Response_WriteLine("<input type=""checkbox"" id=""" & "'" & sqlDataReader.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader.Item("Si_SiteNum") & " - ")
                                            End If
                                            If sqlDataReader.Item("Si_Active") = "No" Then
                                                Response_WriteLine("* ")
                                            End If
                                            Response_WriteLine("" & Replace(sqlDataReader.Item("Si_Name"), "Choose Site", "") & "</input><br/>")
                                        End While
                                        Response_WriteLine("</fieldset>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try
                                Response_WriteLine("</div></p>")
                                Me.ShowADGroupsTable(Me.AdminSite)

                            Case "AddScript"

                                Dim form_ReasonIndex, strUsedReasons

                                If form_Method = "StoreMe" Then
                                    ' new AddScript fields submitted, store them

                                    form_ReasonIndex = Request.Form("form_ReasonIndex")

                                    form_Error = ""
                                    If form_LocationIndex = "" Then
                                        form_Error = form_Error & " Location"
                                    End If
                                    If form_ReasonIndex = "" Then
                                        form_Error = form_Error & " Reason"
                                    End If
                                    If form_Details = "" Then
                                        form_Error = form_Error & " Script"
                                    End If
                                    If form_Notes = "" Then
                                        form_Error = form_Error & " Notes"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to insert

                                        sSqlString = "SELECT tab_Reasons.Re_Index" & " FROM tab_Reasons LEFT JOIN tab_Scripts" & " ON tab_Reasons.Re_Index = tab_Scripts.Sc_ReasonIndex" & " WHERE tab_Scripts.Sc_ReasonIndex = " & form_ReasonIndex & " AND tab_Scripts.Sc_LocationIndex = " & form_LocationIndex & ";"
                                        ' don't add the Sc_Details to this duplicate query as there can only be one script per reason per location anyway
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.HasRows Then
                                                ' truly is safe, it doesn't exist yet.

                                                sSqlString = "INSERT INTO tab_Scripts (Sc_ReasonIndex, Sc_LocationIndex, Sc_Details, Sc_Notes) " & "VALUES (" & form_ReasonIndex & ", " & form_LocationIndex & ", '" & Replace(form_Details, "'", "''") & "', '" & Replace(form_Notes, "'", "''") & "');"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                If InsertTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">New Script for <i>" & Me.GetLocationName(Sc_LocationIndex) & "</i> added successfully.</font></p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">ERROR adding new Script for <i>" & Me.GetLocationName(Sc_LocationIndex) & "</i>.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Add Script", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' record already found for this Script.  Do not add.
                                                Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE. Cannot add Script.<br>")
                                                Response_WriteLine("A script already exists for this Location and Reason.")
                                                Response_WriteLine("</font></p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<Table cellspacing=""0"">")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Script</th></tr>")
                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Location&nbsp;</td>")
                                If form_LocationIndex = 0 Then
                                    Response_WriteLine("<td>---Default---</td><td>This Script is the default for all locations that don't have a custom Script.</td>")
                                Else
                                    Response_WriteLine("<td>" & Me.GetLocationName(form_LocationIndex) & "")
                                    Response_WriteLine("<form name=""frmLinkEditLocationFromESc"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                    Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromESc.submit()""><small>Edit</small></a>")
                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                    Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                    Response_WriteLine("</form>")
                                    Response_WriteLine("</td><td>This is a custom script that is displayed in place of the Default Script for only this location.</td>")
                                End If
                                Response_WriteLine("</tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<form name=""form_Method_AddScript"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddScript"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Reason&nbsp;</td><td>")
                                Response_WriteLine("<select name=""form_ReasonIndex"" class=""form-control"">")
                                Response_WriteLine("<option></option>")
                                strUsedReasons = ""
                                ' include Reasons for this Location's Type only
                                sSqlString = "SELECT tab_Locations.Lo_Type FROM tab_Locations WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If sqlDataReader.Read = False Then
                                        ' strange, can't limit it
                                        sSqlString = "SELECT tab_Reasons.Re_Index, tab_Reasons.Re_Name" & " FROM tab_Reasons" & " WHERE tab_Reasons.Re_Active = 'Yes'" & " ORDER BY tab_Reasons.Re_SortOrder;"
                                    Else
                                        sSqlString = "SELECT tab_Reasons.Re_Index, tab_Reasons.Re_Name" & " FROM tab_Reasons" & " WHERE tab_Reasons.Re_Active = 'Yes'" & " AND tab_Reasons.Re_Type = '" & sqlDataReader.Item("Lo_Type") & "'" & " ORDER BY tab_Reasons.Re_SortOrder;"
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.HasRows Then
                                        ' none found
                                    Else
                                        While sqlDataReader.Read = True
                                            ' exclude Reasons that already exist for this site
                                            sSqlString = "SELECT tab_Scripts.Sc_ReasonIndex FROM tab_Scripts" & " WHERE tab_Scripts.Sc_ReasonIndex = " & sqlDataReader.Item("Re_Index") & " AND tab_Scripts.Sc_LocationIndex = " & form_LocationIndex & ";"

                                            MyCommand2.CommandText = sSqlString

                                            Try
                                                If MyConnection2.State = ConnectionState.Closed Then
                                                    MyConnection2.Open()
                                                End If

                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                If Not sqlDataReader2.Read Then
                                                    ' show it, script does does not exist for this reason at this location
                                                    Response_WriteLine("<option value=""" & sqlDataReader.Item("Re_Index") & """ >" & sqlDataReader.Item("Re_Name") & "</option>")
                                                Else
                                                    ' used already
                                                    ' not selectable option types don't exist in IE
                                                    If strUsedReasons = "" Then
                                                        strUsedReasons = sqlDataReader.Item("Re_Name")
                                                    Else
                                                        strUsedReasons = strUsedReasons & ", " & sqlDataReader.Item("Re_Name")
                                                    End If
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                        End While
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Response_WriteLine("</select> ")
                                Response_WriteLine("</td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Associate this Script with a Reason.<br>")
                                If strUsedReasons <> "" Then
                                    Response_WriteLine("These reasons are already used in this Location, must edit them instead:<br>")
                                    Response_WriteLine("" & strUsedReasons & "")
                                End If
                                Response_WriteLine("</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Script&nbsp;</td>")
                                Response_WriteLine("<td><textarea name=""form_Details"" class=""form-control"" rows=""4"" cols=""80""></textarea></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Enter the Script as it will be read back to the caller</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td>")
                                Response_WriteLine("<td><input type=""text"" name=""form_Notes"" class=""form-control"" value=""Script added " & theDate & """ size=""40"" maxlength=""255""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain the Script</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Script""></center></td></tr>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</Table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p>")
                                Me.ShowScriptsTable(form_LocationIndex)

                            Case "AddHoliday"

                                If form_Method = "StoreMe" Then
                                    ' new Holiday fields submitted, store them

                                    form_Error = ""
                                    If form_HoDate = "" Then
                                        form_Error = form_Error & " Date"
                                    Else
                                        If Not IsDate(form_HoDate) Then
                                            form_Error = form_Error & " valid-Date"
                                        End If
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to insert
                                        form_HoDate = CDate(form_HoDate)
                                        ' #date# for access, 'date' for sSqlString
                                        If _clsMessageVAR.BUsesSqlString = True Then
                                            sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = '" & form_HoDate & "';"
                                        Else
                                            sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = #" & form_HoDate & "#;"
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                ' truly is safe, it doesn't exist yet.

                                                ' #date# for access, 'date' for sSqlString
                                                If _clsMessageVAR.BUsesSqlString = True Then
                                                    sSqlString = "INSERT INTO tab_Holidays (Ho_Date, Ho_Name) VALUES ('" & form_HoDate & "', '" & Replace(form_Name, "'", "''") & "');"
                                                Else
                                                    sSqlString = "INSERT INTO tab_Holidays (Ho_Date, Ho_Name) VALUES (#" & form_HoDate & "#, '" & Replace(form_Name, "'", "''") & "');"
                                                End If
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                If InsertTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">New Holiday <i>" & form_HoDate & "</i> added successfully.</font></p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">ERROR adding new AD Group <i>" & form_HoDate & "</i>.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' reset Application Variable to force Holiday reload
                                                Application("Ho.CrDate") = DateAdd("d", -1, theDate)

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Add Holiday", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' record already found for this AD Group.  Do not add.
                                                Response_WriteLine("<p><font color=""red"">ERROR DUPLICATE. Cannot add new Holiday.<br>")
                                                Response_WriteLine("Date <i>" & form_HoDate & "</i> already exists.</font></p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"
                                Response_WriteLine("<p>")
                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                Response_WriteLine("<Table cellspacing=""0"">")
                                Response_WriteLine("<form name=""form_Method_AddHoliday"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddHoliday"">")
                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Add a Holiday</th></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Date&nbsp;</td>")
                                Response_WriteLine("<td><input type=""text"" name=""form_HoDate"" class=""form-control"" value="""" size=""10"" maxlength=""10""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">MM/DD/YYYY</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Holiday Name&nbsp;</td>")
                                Response_WriteLine("<td><input type=""text"" name=""form_Name"" class=""form-control"" value="""" size=""40"" maxlength=""50""></td>")
                                Response_WriteLine("<td bgcolor=""#eeeeee"">Follow naming style as seen on OPM.gov.  Open in new window:<br>")
                                Response_WriteLine("<a href=""http://www.opm.gov/operating_status_schedules/fedhol/"" target=""_blank"">http://www.opm.gov/operating_status_schedules/fedhol/</a><br>")
                                Response_WriteLine("</td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Holiday""></center></td></tr>")
                                Response_WriteLine("</form>")
                                Response_WriteLine("</Table>")
                                Response_WriteLine("</td></tr></table>")
                                Response_WriteLine("</p>")
                                Me.ShowHolidaysTable()

                            Case "EditSite"
                                If form_Method = "StoreMe" Then
                                    ' new EditSite fields submitted, store them

                                    form_Error = ""

                                    ' form_SiteNum is not editable
                                    ' form_SortOrder is guaranteed to have a value

                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to update

                                        sSqlString = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & form_SiteNum & "';"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">Error - " & form_SiteNum & " not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            Else
                                                ' store new sort order
                                                If CStr(sqlDataReader.Item("Si_SiteOrder")) <> Replace(form_SortOrder, "AAA", "") Then
                                                    Me.ReSortSite(form_SiteNum, form_SortOrder)

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Site", "Sort Order changed to " & form_SortOrder & " for SiteNum = " & form_SiteNum)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Si_Name") <> form_Name Then
                                                    UpdateTableRecord("UPDATE tab_Sites SET tab_Sites.Si_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Sites.Si_SiteNum = '" & form_SiteNum & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Name updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Name.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Site", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Si_Active") <> form_Active Then
                                                    UpdateTableRecord("UPDATE tab_Sites SET tab_Sites.Si_Active = '" & form_Active & "' WHERE tab_Sites.Si_SiteNum = '" & form_SiteNum & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Active updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Active.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Site", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"						

                                sSqlString = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & form_SiteNum & "';"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Site, """ & form_SiteNum & """ not found in database.</font></p>")
                                    Else
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<table cellspacing=""0"">")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit Site</th></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>SiteNum</b>&nbsp;</td><td><b>" & form_SiteNum & "</b></td>")
                                        Response_WriteLine("<td>Cannot change the Site Number.<br>")
                                        Response_WriteLine("Must instead create a new Site.</td></tr>")
                                        tempNames = Me.GetSiteNames(True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">Strange, No Sites found yet you are editing this one</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                            ' prevent "Site Fee" from getting bolded by matches to "Site" by also matching what follows the SiteName
                                            If Not IsDBNull(sqlDataReader.Item("Si_Name")) Then
                                                tempNames = Replace(tempNames, sqlDataReader.Item("Si_Name") & " <form", "<b>" & sqlDataReader.Item("Si_Name") & "</b> <form")
                                            End If
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Sites&nbsp;</td><td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddSiteFromES"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddSiteFromES.submit()""><small>Add Site</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddSite"">")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        tempNames = Me.GetSiteLocationNames(form_SiteNum, True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">No Locations Exist Yet</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Locations&nbsp;</td><td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddLocationFromES"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddLocationFromES.submit()""><small>Add Location</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddLocation"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<form name=""form_Method_EditSite"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                        sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_SiteOrder, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites WHERE tab_Sites.Si_SiteNum <> '000' ORDER BY tab_Sites.Si_SiteOrder ASC;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand2.CommandText = sSqlString

                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                ' should never get here as it exists already
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">First Site will be SortOrder=10.<br>")
                                                Response_WriteLine("This is the order that the Site will appear in the list of Sites.</td>")
                                            Else
                                                Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                                maxSortOrder = 10
                                                While sqlDataReader2.Read = True
                                                    If sqlDataReader2.Item("Si_SiteOrder") > maxSortOrder Then
                                                        maxSortOrder = sqlDataReader2.Item("Si_SiteOrder")
                                                    End If
                                                    If sqlDataReader2.Item("Si_SiteNum") = form_SiteNum Then
                                                        Response_WriteLine("<option selected value=""AAA" & sqlDataReader2.Item("Si_SiteOrder") & """>" & sqlDataReader2.Item("Si_SiteOrder") & "</option>")
                                                    Else
                                                        Response_WriteLine("<option value=""AAA" & sqlDataReader2.Item("Si_SiteOrder") & """>" & sqlDataReader2.Item("Si_SiteOrder") & " - ")
                                                        If sqlDataReader2.Item("Si_Active") = "No" Then
                                                            Response_WriteLine("* ")
                                                        End If
                                                        Response_WriteLine("" & sqlDataReader2.Item("Si_SiteNum") & " - " & sqlDataReader2.Item("Si_Name") & "</option>")
                                                    End If
                                                End While
                                                If sqlDataReader.Item("Si_SiteOrder") < maxSortOrder Then
                                                    Response_WriteLine("<option value=""ZZZ"">Move to End</option>")
                                                Else
                                                    ' no need to give a "ZZZ move to end" option, it's already at the end
                                                End If
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected.<br>")
                                                Response_WriteLine("This is the order that the Site will appear in the list of Sites.</td>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" size=""30"" value=""" & Replace(sqlDataReader.Item("Si_Name"), """", "&#34;") & """ maxlength=""50""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">example: Madison</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Active"" class=""form-control"">")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("Si_Active") = "Yes" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""Yes"">Yes</option>")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("Si_Active") = "No" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""No"">No</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Site available to receive new Messages<br>")
                                        Response_WriteLine("No = Site not available to receive new Messages</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Site""></center></td></tr>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowSitesTable(form_SiteNum)

                            Case "EditLocation"
                                If form_Method = "StoreMe" Then
                                    ' new EditLocation fields submitted, store them

                                    form_Error = ""

                                    ' SiteNum is not editable
                                    ' form_LocationIndex is guaranteed to have a value
                                    ' form_SortOrder is guaranteed to have a value

                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Type = "" Then
                                        form_Error = form_Error & " Type"
                                    Else
                                        If form_Type = "None Found" Then
                                            form_Error = form_Error & " Type(create-Types-first)"
                                        End If
                                    End If
                                    If form_Error = "" Then
                                        ' safe to update

                                        sSqlString = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If sqlDataReader.Read = False Then
                                                Response_WriteLine("<p><font color=""red"">Error - " & form_LocationIndex & " not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            Else
                                                ' store new sort order
                                                If CStr(sqlDataReader.Item("Lo_SortOrder")) <> Replace(form_SortOrder, "AAA", "") Then
                                                    Me.ReSortLocation(form_LocationIndex, form_SortOrder)

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Location", "Sort Order changed to " & form_SortOrder & " for Index = " & form_LocationIndex)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Lo_Name") <> form_Name Then
                                                    UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Name updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Name.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Location", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Lo_Type") <> form_Type Then
                                                    UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_Type = '" & Replace(form_Type, "'", "''") & "' WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Type updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Type.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Location", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Lo_Active") <> form_Active Then
                                                    UpdateTableRecord("UPDATE tab_Locations SET tab_Locations.Lo_Active = '" & form_Active & "' WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Active updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Active.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Location", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"						

                                sSqlString = "SELECT * FROM tab_Locations WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Location, """ & form_LocationIndex & """ not found in database.</font></p>")
                                    Else
                                        ' load SiteNum to be used after this table - with the ShowSitesTable routine call
                                        form_SiteNum = sqlDataReader.Item("Lo_SiteNum")
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<table cellspacing=""0"">")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit Location</th></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right""><b>Index</b>&nbsp;</td><td colspan=""2""><b>" & sqlDataReader.Item("Lo_Index") & "</b></td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td>")
                                        Response_WriteLine("<td><b>" & sqlDataReader.Item("Lo_SiteNum") & " - " & Me.GetSiteName(sqlDataReader.Item("Lo_SiteNum")) & "</b>")
                                        Response_WriteLine("<form name=""frmLinkEditSiteFromEL"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromEL.submit()""><small>Edit</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("<td>Cannot change the Site.<br>")
                                        Response_WriteLine("Must instead create the Location under a new Site.</td></tr>")
                                        tempNames = Me.GetSiteLocationNames(sqlDataReader.Item("Lo_SiteNum"), True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">Strange, No Locations found yet you are editing this one</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                            ' prevent "Name10" from getting bolded by matches to "Name1" by also matching what follows the name
                                            If Not IsDBNull(sqlDataReader.Item("Lo_Name")) Then
                                                tempNames = Replace(tempNames, sqlDataReader.Item("Lo_Name") & " <form", "<b>" & sqlDataReader.Item("Lo_Name") & "</b> <form")
                                            End If
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Locations&nbsp;</td><td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddLocationFromEL"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddLocationFromEL.submit()""><small>Add Location</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddLocation"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        tempNames = Me.GetLocationTeamNames(form_LocationIndex, True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">No Teams Exist Yet</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Teams&nbsp;</td><td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddTeamFromEL"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddTeamFromEL.submit()""><small>Add Team</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddTeam"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee""><td colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<form name=""form_Method_EditLocation"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                        ' show all types in sort order
                                        sSqlString = "SELECT tab_Locations.Lo_Index, tab_Locations.Lo_SortOrder, tab_Locations.Lo_Name, tab_Locations.Lo_Active" & " FROM tab_Locations" & " WHERE tab_Locations.Lo_SiteNum = '" & sqlDataReader.Item("Lo_SiteNum") & "'" & " ORDER BY tab_Locations.Lo_SortOrder ASC;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand2.CommandText = sSqlString

                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                ' should never get here as it exists already
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">First Location will be SortOrder=10.<br>")
                                                Response_WriteLine("This is the order that the Location will appear in the list of Locations.</td>")
                                            Else
                                                Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                                maxSortOrder = 10
                                                While sqlDataReader2.Read = True
                                                    If sqlDataReader2.Item("Lo_SortOrder") > maxSortOrder Then
                                                        maxSortOrder = sqlDataReader2.Item("Lo_SortOrder")
                                                    End If
                                                    If CStr(sqlDataReader2.Item("Lo_Index")) = form_LocationIndex Then
                                                        Response_WriteLine("<option selected value=""AAA" & sqlDataReader2.Item("Lo_SortOrder") & """>" & sqlDataReader2.Item("Lo_SortOrder") & "</option>")
                                                    Else
                                                        Response_WriteLine("<option value=""AAA" & sqlDataReader2.Item("Lo_SortOrder") & """>" & sqlDataReader2.Item("Lo_SortOrder") & " - ")
                                                        If sqlDataReader2.Item("Lo_Active") = "No" Then
                                                            Response_WriteLine("* ")
                                                        End If
                                                        Response_WriteLine("" & sqlDataReader2.Item("Lo_Name") & "</option>")
                                                    End If
                                                End While
                                                If sqlDataReader.Item("Lo_SortOrder") < maxSortOrder Then
                                                    Response_WriteLine("<option value=""ZZZ"">Move to End</option>")
                                                Else
                                                    ' no need to give a "ZZZ move to end" option, it's already at the end
                                                End If
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected.<br>")
                                                Response_WriteLine("This is the order that the Location will appear in the list of Locations.</td>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" size=""50"" value=""" & Replace(sqlDataReader.Item("Lo_Name"), """", "&#34;") & """ maxlength=""255""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">example: Madison West Annex</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Type"" class=""form-control"">")
                                        optionItem = ""
                                        sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons"
                                        If Me.AdminType = "All" Then
                                            ' don't limit by Type, meaning show all types
                                        Else
                                            ' limit by Type
                                            sSqlString = sSqlString & " WHERE tab_Reasons.Re_Type = '" & Me.AdminType & "'"
                                        End If
                                        sSqlString = sSqlString & " ORDER BY tab_Reasons.Re_Type;"

                                        MyCommand2.CommandText = sSqlString

                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                optionItem = "<option value=""None Found"">None Found</option>" & vbCrLf
                                            Else
                                                While sqlDataReader2.Read = True
                                                    ' Only include PACT as per John P. TJD
                                                    If sqlDataReader2.Item("REASONTYPE") = "PACT" Then
                                                        optionItem = optionItem & "<option value=""" & sqlDataReader2.Item("REASONTYPE") & """"
                                                        If sqlDataReader.Item("Lo_Type") = sqlDataReader2.Item("REASONTYPE") Then
                                                            optionItem = optionItem & " selected"
                                                        End If
                                                        optionItem = optionItem & ">" & sqlDataReader2.Item("REASONTYPE") & "</option>" & vbCrLf
                                                    End If
                                                End While
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        Response.Write(optionItem)
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Choose the Type that applies to all Teams in this Location</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Active"" class=""form-control"">")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("Lo_Active") = "Yes" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""Yes"">Yes</option>")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("Lo_Active") = "No" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""No"">No</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Location available to receive new Messages<br>")
                                        Response_WriteLine("No = Location not available to receive new Messages</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Location""></center></td></tr>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowLocationsTable(form_SiteNum)

                            Case "EditTeam"
                                If form_Method = "StoreMe" Then
                                    ' new EditTeam fields submitted, store them

                                    form_Error = ""

                                    ' LocationIndex is not editable
                                    ' form_TeamIndex is guaranteed to have a value
                                    ' form_SortOrder is guaranteed to have a value
                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Notes = "" Then
                                        form_Error = form_Error & " Notes"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to update

                                        sSqlString = "SELECT * FROM tab_Teams WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">Error - " & form_TeamIndex & " not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            Else
                                                ' store new sort order
                                                If CStr(sqlDataReader.Item("Te_SortOrder")) <> Replace(form_SortOrder, "AAA", "") Then
                                                    Me.ReSortTeam(form_TeamIndex, form_SortOrder)

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Team", "Sort Order changed to " & form_SortOrder & " for Index = " & form_TeamIndex)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Te_Name") <> form_Name Then
                                                    UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Name updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Name.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Team", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("Te_Active") <> form_Active Then
                                                    UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_Active = '" & form_Active & "' WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Active updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Active.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Team", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If

                                                    ' BONUS - check this Team for Assigned Messages.
                                                    ' This is STRICTLY a check for when toggling to InActive.
                                                    If form_Active = "No" Then
                                                        sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages WHERE tab_Messages.Msg_Completed IS NULL AND tab_Messages.Msg_TeamIndex = " & form_TeamIndex & ";"
                                                        'On Error Resume Next

                                                        MyCommand2.CommandText = sSqlString

                                                        Try
                                                            If MyConnection2.State = ConnectionState.Closed Then
                                                                MyConnection2.Open()
                                                            End If

                                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                                            If Err.Number = 0 Then
                                                                If sqlDataReader2.Read() Then
                                                                    thecount = sqlDataReader2.Item("THECOUNT")
                                                                    If thecount > 0 Then
                                                                        If thecount = 1 Then
                                                                            Response_WriteLine("<p><font color=""red"">Warning: There is 1 active Message for this Inactive Team.<br>")
                                                                            Response_WriteLine("Suggestion: Transfer the message or close it out.</font></p>")
                                                                        Else
                                                                            Response_WriteLine("<p><font color=""red"">Warning: There are " & thecount & " active Messages for this Inactive Team.<br>")
                                                                            Response_WriteLine("Suggestion: Transfer the messages or close them out.</font></p>")
                                                                        End If
                                                                    Else
                                                                        Response_WriteLine("<p><font color=""navy"">Note - 0 active Messages for this Inactive Team.</font></p>")
                                                                    End If
                                                                End If
                                                            Else
                                                                Response_WriteLine("<p><font color=""red"">ERROR checking for Active Messages.</font></p>")
                                                            End If

                                                        Catch ex As Exception
                                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                        Finally
                                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                        End Try

                                                    End If

                                                Else
                                                    ' skip, not changed
                                                End If

                                                If IsDBNull(sqlDataReader.Item("Te_Notes")) Then
                                                    memoNotes = ""
                                                Else
                                                    memoNotes = sqlDataReader.Item("Te_Notes")
                                                End If
                                                If memoNotes <> form_Notes Then
                                                    UpdateTableRecord("UPDATE tab_Teams SET tab_Teams.Te_Notes = '" & Replace(form_Notes, "'", "''") & "' WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Notes updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Notes.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Team", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"						

                                sSqlString = "SELECT * FROM tab_Teams WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Team, """ & form_TeamIndex & """ not found in database.</font></p>")
                                    Else
                                        ' load LocationIndex to be used after this table - with the ShowTeamsTable routine call
                                        form_LocationIndex = sqlDataReader.Item("Te_LocationIndex")
                                        form_SiteNum = Me.GetSiteNum(form_LocationIndex)
                                        If IsDBNull(sqlDataReader.Item("Te_Notes")) Then
                                            memoNotes = "Edit by " & Me.UserName & " on " & theDate
                                        Else
                                            memoNotes = sqlDataReader.Item("Te_Notes")
                                        End If
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<table cellspacing=""0"">")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit Team</th></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right""><b>Index</b>&nbsp;</td><td colspan=""2""><b>" & sqlDataReader.Item("Te_Index") & "</b></td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td>")
                                        Response_WriteLine("<td colspan=""2""><b>" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & "</b>")
                                        Response_WriteLine("<form name=""frmLinkEditSiteFromET"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromET.submit()""><small>Edit</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Location</b>&nbsp;</td>")
                                        Response_WriteLine("<td width=""35%""><b>" & Me.GetLocationName(form_LocationIndex) & "</b>")
                                        Response_WriteLine("<form name=""frmLinkEditLocationFromET"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromET.submit()""><small>Edit</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("<td>Cannot change the Location.<br>")
                                        Response_WriteLine("Must instead create the Team under a new Location.</td></tr>")
                                        tempNames = Me.GetLocationTeamNames(form_LocationIndex, True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">Strange, No Teams found yet you are editing this one</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                            ' prevent "Teamlet 10" from getting bolded by matches to "Teamlet 1" by also matching what follows the team name
                                            If Not IsDBNull(sqlDataReader.Item("Te_Name")) Then
                                                tempNames = Replace(tempNames, sqlDataReader.Item("Te_Name") & " <form", "<b>" & sqlDataReader.Item("Te_Name") & "</b> <form")
                                            End If
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Teams&nbsp;</td><td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddTeamFromET"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddTeamFromET.submit()""><small>Add Team</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddTeam"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        tempNames = Me.GetTeamMemberNames(form_TeamIndex, True, True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">No Members Exist Yet</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Team&nbsp;Members&nbsp;</td><td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddMemberFromET"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddMemberFromET.submit()""><small>Add Member</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        tempEmail = Me.GetTeamMemberNewEmails(form_TeamIndex)
                                        If tempEmail = "" Then
                                            tempEmail = "<font color=""red"">No Email Recipients for New Messages</font>"
                                        Else
                                            tempEmail = LCase(tempEmail)
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">New&nbsp;Message&nbsp;Emails&nbsp;</td><td colspan=""2"">" & tempEmail & "</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<form name=""form_Method_EditTeam"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                        sSqlString = "SELECT tab_Teams.Te_Index, tab_Teams.Te_SortOrder, tab_Teams.Te_Name, tab_Teams.Te_Active FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & sqlDataReader.Item("Te_LocationIndex") & " ORDER BY tab_Teams.Te_SortOrder ASC;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand2.CommandText = sSqlString

                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                ' should never get here as it exists already
                                                Response_WriteLine("<td bgcolor=""#eeeeee"" width=""1%"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">First Team will be SortOrder=10.<br>")
                                                Response_WriteLine("This is the order that the Team will appear in the list of Teams.</td>")
                                            Else
                                                Response_WriteLine("<td width=""35%""><select name=""form_SortOrder"" class=""form-control"">")
                                                maxSortOrder = 10
                                                While sqlDataReader2.Read = True
                                                    If sqlDataReader2.Item("Te_SortOrder") > maxSortOrder Then
                                                        maxSortOrder = sqlDataReader2.Item("Te_SortOrder")
                                                    End If
                                                    If CStr(sqlDataReader2.Item("Te_Index")) = form_TeamIndex Then
                                                        Response_WriteLine("<option selected value=""AAA" & sqlDataReader2.Item("Te_SortOrder") & """>" & sqlDataReader2.Item("Te_SortOrder") & "</option>")
                                                    Else
                                                        Response_WriteLine("<option value=""AAA" & sqlDataReader2.Item("Te_SortOrder") & """>" & sqlDataReader2.Item("Te_SortOrder") & " - ")
                                                        If sqlDataReader2.Item("Te_Active") = "No" Then
                                                            Response_WriteLine("* ")
                                                        End If
                                                        Response_WriteLine("" & sqlDataReader2.Item("Te_Name") & "</option>")
                                                    End If
                                                End While
                                                If sqlDataReader.Item("Te_SortOrder") < maxSortOrder Then
                                                    Response_WriteLine("<option value=""ZZZ"">Move to End</option>")
                                                Else
                                                    ' no need to give a "ZZZ move to end" option, it's already at the end
                                                End If
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected.<br>")
                                                Response_WriteLine("This is the order that the Team will appear in the list of Teams.</td>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name&nbsp;</td>")
                                        Response_WriteLine("<td width=""35%""><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(sqlDataReader.Item("Te_Name"), """", "&#34;") & """ size=""50"" maxlength=""255""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">example: PACT Gold Team 1</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td>")
                                        Response_WriteLine("<td width=""35%""><select name=""form_Active"" class=""form-control"">")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("Te_Active") = "Yes" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""Yes"">Yes</option>")
                                        Response_WriteLine("							<option ")
                                        If sqlDataReader.Item("Te_Active") = "No" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""No"">No</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Team available to receive new Messages<br>")
                                        Response_WriteLine("No = Team not available to receive new Messages</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top"" width=""1%""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td><td><input type=""text"" name=""form_Notes"" class=""form-control"" value=""" & Replace(memoNotes, """", "&#34;") & """ size=""50"" maxlength=""255""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain Team settings</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Team""></center></td></tr>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowTeamsTable(form_LocationIndex)

                            Case "EditMember"
                                Dim oldTitle, oldEmailNew, oldEmailAssign, oldEmailStatus, oldShowOn, oldSID, oldNotes
                                Dim newUsername, newName, newTitle, newEmail, newEmailNew, newEmailAssign, newEmailStatus, newShowOn, newActive, newSID, newNotes

                                If form_Submit = "Choose Selected Account" Then
                                    If ADloop = "x" Then
                                        Response_WriteLine("<p><font color=""red"">Selection cancelled.</font></p>")
                                    Else
                                        If ADloop = "" Then
                                            Response_WriteLine("<p><font color=""red"">Selection submitted but nothing was chosen.</font></p>")
                                        Else
                                            ' name chosen
                                            Response_WriteLine("<p><font color=""green"">Selection complete, auto-filling fields: [Title], Name, Username, SID, Email</font></p>")
                                        End If
                                    End If
                                End If

                                Select Case form_Submit
                                    Case "Look Up"
                                        ' name entered, "Look Up" submitted, load username and email from AD
                                        strADResults = Me.ADNameSearch(form_Name)
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("strADResults=" & strADResults & "<br>")
                                        End If
                                        If strADResults <> "" Then
                                            ' One or more hits found, show the form to pick the right one
                                            ' strFirstname & "_^_" & strLastname & "_^_" & strEmail & "_^_" & strTitle & "_^_" & strFullname & "_^_" & sDomain\strUsername & "_^_" & strSID & "_^__ROW_"

                                            ' These 3 are not passed through with form_variable, used as ADT, ADFULL (ADF and ADL), ADE instead
                                            'form_Title
                                            'form_Name
                                            'form_Email
                                            Response_WriteLine("<form name=""frmMethodEditMemberAD"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_MemberIndex"" value=""" & form_MemberIndex & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""ChoseAD"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_SortOrder"" value=""" & Replace(form_SortOrder, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_EmailNew"" value=""" & form_EmailNew & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_EmailAssign"" value=""" & form_EmailAssign & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_EmailStatus"" value=""" & form_EmailStatus & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_ShowOn"" value=""" & form_ShowOn & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Active"" value=""" & form_Active & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Notes"" value=""" & Replace(form_Notes, """", "&#34;") & """>")
                                            Response_WriteLine("<table>")
                                            Response_WriteLine("<tr><th colspan=""5"" bgcolor=""#d6dbe9"">Choose the closest match or cancel</th></tr>")
                                            strADResults = strADResults & "zzz"

                                            ADrows = Split(strADResults, "_ROW_")
                                            ADloop = 0
                                            Do While ADrows(ADloop) <> "zzz"

                                                ADarray = Split(ADrows(ADloop), "_^_")
                                                If ADarray(0) <> "" Then
                                                    ADF = ADarray(0)
                                                    If ADarray(1) <> "zzz" Then
                                                        ADL = ADarray(1)
                                                        If ADarray(2) <> "zzz" Then
                                                            ADE = ADarray(2)
                                                            If ADarray(3) <> "zzz" Then
                                                                ADT = ADarray(3)
                                                                If ADarray(4) <> "zzz" Then
                                                                    ADFULL = ADarray(4)
                                                                    If ADarray(5) <> "zzz" Then
                                                                        ADU = ADarray(5)
                                                                        If ADarray(6) <> "zzz" Then
                                                                            ADSID = ADarray(6)
                                                                        End If
                                                                    End If
                                                                End If
                                                            End If
                                                        End If
                                                    End If
                                                End If
                                                ' all fields could in theory have a " in them except for the SID
                                                Response_WriteLine("<input type=""hidden"" name=""ADF" & ADloop & """ value=""" & Replace(ADF, """", "&#34;") & """>")
                                                Response_WriteLine("<input type=""hidden"" name=""ADL" & ADloop & """ value=""" & Replace(ADL, """", "&#34;") & """>")
                                                Response_WriteLine("<input type=""hidden"" name=""ADE" & ADloop & """ value=""" & Replace(ADE, """", "&#34;") & """>")
                                                Response_WriteLine("<input type=""hidden"" name=""ADT" & ADloop & """ value=""" & Replace(ADT, """", "&#34;") & """>")
                                                Response_WriteLine("<input type=""hidden"" name=""ADFULL" & ADloop & """ value=""" & Replace(ADFULL, """", "&#34;") & """>")
                                                Response_WriteLine("<input type=""hidden"" name=""ADU" & ADloop & """ value=""" & Replace(ADU, """", "&#34;") & """>")
                                                Response_WriteLine("<input type=""hidden"" name=""ADSID" & ADloop & """ value=""" & ADSID & """>")
                                                If ADloop Mod 2 = 0 Then
                                                    Response_WriteLine("<tr bgcolor=""#eeeeee""><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                    Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                                Else
                                                    Response_WriteLine("<tr><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                    Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                                End If
                                                ADloop = ADloop + 1
                                            Loop
                                            ' these values were the last of the loop so re-initialize
                                            ADloop = ""
                                            ADF = ""
                                            ADL = ""
                                            ADE = ""
                                            ADT = ""
                                            ADFULL = ""
                                            ADU = ""
                                            ADSID = ""
                                            Response_WriteLine("<tr><td>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADFULLx"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADEx"" value=""" & Replace(form_Email, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADUx"" value=""" & Replace(form_Username, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADSIDx"" value=""" & form_SID & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADTx"" value=""" & Replace(form_Title, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""radio"" name=""form_AD"" value=""x""></td>")
                                            Response_WriteLine("<td colspan=""4"">Cancel</td>")
                                            Response_WriteLine("</tr>")
                                            Response_WriteLine("<tr><td colspan=""5""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Choose Selected Account""></center></td></tr>")
                                            Response_WriteLine("</table>")
                                            Response_WriteLine("</form>")
                                        End If

                                    Case "Change Checked Fields Too"
                                        ' used to trigger checkbox updates to other teams
                                        '    form_MemberIndex = nnn  (the new fields to use if updating to other old username)
                                        ' form_MemberIndex already loaded

                                        ' loop through other teams with matching oldUserName
                                        ' if the Index matches and is checked to confirm updating, make all fields match the source member's setup.
                                        ' change Username, Email, Name, Title, EmailNew, EmailAssign, EmailStatus, ShowOn, Active fields. 
                                        sSqlString = "SELECT * FROM tab_Members WHERE tab_Members.Me_Index = " & form_MemberIndex & ";"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">ERROR - Source Team not found. Restart at the Edit Setup screen.</font></p>")
                                            Else
                                                Dim EXTRAMSG
                                                EXTRAMSG = ""

                                                ' store as a variable for reference
                                                form_TeamIndex = sqlDataReader.Item("Me_TeamIndex")

                                                ' load new values for later reference.  All are guaranteed not to be NULL
                                                newUsername = sqlDataReader.Item("Me_Username")
                                                newName = sqlDataReader.Item("Me_Name")
                                                newTitle = sqlDataReader.Item("Me_Title")
                                                newEmail = sqlDataReader.Item("Me_Email")
                                                newEmailNew = sqlDataReader.Item("Me_EmailNew")
                                                newEmailAssign = sqlDataReader.Item("Me_EmailAssign")
                                                newEmailStatus = sqlDataReader.Item("Me_EmailStatus")
                                                newShowOn = sqlDataReader.Item("Me_ShowOn")
                                                newActive = sqlDataReader.Item("Me_Active")
                                                newSID = sqlDataReader.Item("Me_SID")
                                                newNotes = sqlDataReader.Item("Me_Notes")

                                                ' get the rest of the teams that use the original/old username
                                                ' form_Username is the old username, passed through the form yet.
                                                sSqlString = "SELECT * FROM tab_Members WHERE" & " tab_Members.Me_Username LIKE '" & Replace(form_Username, "'", "''") & "'" & " AND tab_Members.Me_Index <> " & form_MemberIndex & ";"

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If Not sqlDataReader2.HasRows Then
                                                        Response_WriteLine("<p><font color=""red"">No other teams found, nothing to update.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p>Original values shown.<br>")
                                                        Response_WriteLine("Values that are changing are shown in <font color=""green""><b>green font</b></font>.<br>")
                                                        Response_WriteLine("Values that already match are shown in black font.")
                                                        Response_WriteLine("<table>")
                                                        Response_WriteLine("<tr bgcolor=""#d6dbe9"">")
                                                        Response_WriteLine("<th>&nbsp;</th>")
                                                        Response_WriteLine("<th>Team</th>")
                                                        Response_WriteLine("<th>Username</th>")
                                                        Response_WriteLine("<th>SID</th>")
                                                        Response_WriteLine("<th>Name</th>")
                                                        Response_WriteLine("<th>Title</th>")
                                                        Response_WriteLine("<th>Email</th>")
                                                        Response_WriteLine("<th>E-New</th>")
                                                        Response_WriteLine("<th>E-Assign</th>")
                                                        Response_WriteLine("<th>E-Status</th>")
                                                        Response_WriteLine("<th>Show</th>")
                                                        Response_WriteLine("<th>Active</th>")
                                                        Response_WriteLine("<th>Notes</th>")
                                                        Response_WriteLine("</tr>")
                                                        ' sqlDataReader2 refers to ORIGINAL values (referenced as oldXxxxxx variables)
                                                        ' sqlDataReader refers to NEW values (referenced as newXxxxxx variables)
                                                        While sqlDataReader2.Read = True

                                                            ' load original values for later reference
                                                            oldIndex = sqlDataReader2.Item("Me_Index")
                                                            oldTeamIndex = sqlDataReader2.Item("Me_TeamIndex")
                                                            oldUsername = sqlDataReader2.Item("Me_Username")
                                                            oldName = sqlDataReader2.Item("Me_Name")
                                                            oldTitle = sqlDataReader2.Item("Me_Title")
                                                            oldEmail = sqlDataReader2.Item("Me_Email")
                                                            oldEmailNew = sqlDataReader2.Item("Me_EmailNew")
                                                            oldEmailAssign = sqlDataReader2.Item("Me_EmailAssign")
                                                            oldEmailStatus = sqlDataReader2.Item("Me_EmailStatus")
                                                            oldShowOn = sqlDataReader2.Item("Me_ShowOn")
                                                            oldActive = sqlDataReader2.Item("Me_Active")
                                                            oldSID = sqlDataReader2.Item("Me_SID")
                                                            oldNotes = sqlDataReader2.Item("Me_Notes")

                                                            ' most fields are guaranteed not to be NULL, but converting to "" just in case
                                                            ' old Title could be a NULL value before it became required
                                                            ' old SID could be a NULL value before it became required
                                                            ' old Notes could be a NULL value before it became required
                                                            If IsDBNull(oldUsername) Then oldUsername = ""
                                                            If IsDBNull(oldName) Then oldName = ""
                                                            If IsDBNull(oldTitle) Then oldTitle = ""
                                                            If IsDBNull(oldEmail) Then oldEmail = ""
                                                            If IsDBNull(oldEmailNew) Then oldEmailNew = ""
                                                            If IsDBNull(oldEmailAssign) Then oldEmailAssign = ""
                                                            If IsDBNull(oldEmailStatus) Then oldEmailStatus = ""
                                                            If IsDBNull(oldShowOn) Then oldShowOn = ""
                                                            If IsDBNull(oldActive) Then oldActive = ""
                                                            If IsDBNull(oldSID) Then oldSID = ""
                                                            If IsDBNull(oldNotes) Then oldNotes = ""

                                                            ' Sample: <input type="checkbox" name="form_Check_1529">
                                                            If Request.Form("form_Check_" & oldIndex) = "on" Then
                                                                ' chosen as destination to replace, update each different field
                                                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top"">")
                                                                Response_WriteLine("<td bgcolor=""white""><font color=""green"">Updating:</font></td>")
                                                                Response_WriteLine("<td bgcolor=""white"">" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</td>")
                                                                If newUsername <> oldUsername Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldUsername & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Username = '" & Replace(newUsername, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">Username updated successfully"
                                                                        EXTRAMSG = EXTRAMSG & " for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Username"
                                                                        EXTRAMSG = EXTRAMSG & " for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If

                                                                    ' BONUS - check this member's tab_Messages.Msg_Assigned field to see if that now needs adjusting for OPEN messages
                                                                    ' search Messages for old username as Find/Replace was not yet done on OTHER TEAMS.
                                                                    sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(oldUsername, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & oldTeamIndex & " AND tab_Messages.Msg_Completed IS NULL;"

                                                                    MyCommand3.CommandText = sSqlString

                                                                    Try
                                                                        If MyConnection3.State = ConnectionState.Closed Then
                                                                            MyConnection3.Open()
                                                                        End If

                                                                        sqlDataReader3 = MyCommand3.ExecuteReader

                                                                        If sqlDataReader3.Read = True Then
                                                                            thecount = sqlDataReader3.Item("THECOUNT")

                                                                            If thecount > 0 Then
                                                                                ' Found one, fix it.
                                                                                ' search Messages for old username as Find/Replace was not yet done on OTHER TEAMS.
                                                                                UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Assigned = '" & Replace(newUsername, "'", "''") & "'" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(oldUsername, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & oldTeamIndex & " AND tab_Messages.Msg_Completed IS NULL;")
                                                                                'On Error Resume Next
                                                                                If Err.Number = 0 Then
                                                                                    EXTRAMSG = EXTRAMSG & "<table><tr><td><font color=""navy"">"
                                                                                    EXTRAMSG = EXTRAMSG & "Note - Old Username found in " & thecount & " assigned Open Team Message(s).<br>"
                                                                                    EXTRAMSG = EXTRAMSG & "Replaced username for " & thecount & " assigned Open Team Messages"
                                                                                    EXTRAMSG = EXTRAMSG & " for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>."
                                                                                    EXTRAMSG = EXTRAMSG & "</font></td></tr></table>"
                                                                                Else
                                                                                    EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Open Messages assigned to old username <i>" & oldUsername & "</i><br>"
                                                                                    EXTRAMSG = EXTRAMSG & "with new username <i>" & form_Username & "</i>"
                                                                                    EXTRAMSG = EXTRAMSG & " for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>.</font><br>"
                                                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                                End If
                                                                                'On Error GoTo 0

                                                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                                errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                                If errstore <> "Success" Then
                                                                                    EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                                End If
                                                                            Else
                                                                                EXTRAMSG = EXTRAMSG & "<font color=""navy"">Note - Old Username not found in Assigned Open Messages, nothing to auto-correct"
                                                                                EXTRAMSG = EXTRAMSG & " for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>.</font><br>"
                                                                            End If
                                                                        End If

                                                                    Catch ex As Exception
                                                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                                    Finally
                                                                        If MyConnection3.State = ConnectionState.Open Then MyConnection3.Close()
                                                                        If (Not sqlDataReader3 Is Nothing) Then sqlDataReader3.Close()
                                                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                                    End Try

                                                                Else
                                                                    Response_WriteLine("<td>" & oldUsername & "</td>")
                                                                End If

                                                                If newSID <> oldSID Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldSID & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SID = '" & Replace(newSID, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">SID updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating SID.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font></p>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldSID & "</td>")
                                                                End If

                                                                If newName <> oldName Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldName & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Name = '" & Replace(newName, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">Name updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Name.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font></p>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldName & "</td>")
                                                                End If

                                                                If newTitle <> oldTitle Then
                                                                    ' old Title potentially was NULL vlaue
                                                                    If oldTitle = "" Then
                                                                        Response_WriteLine("<td>&nbsp;</td>")
                                                                    Else
                                                                        Response_WriteLine("<td><font color=""green""><b>" & oldTitle & "</b></font></td>")
                                                                    End If
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Title = '" & Replace(newTitle, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">Title updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Title.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldTitle & "</td>")
                                                                End If

                                                                If newEmail <> oldEmail Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldEmail & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Email = '" & Replace(newEmail, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">Email updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Email.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldEmail & "</td>")
                                                                End If

                                                                If newEmailNew <> oldEmailNew Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldEmailNew & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_EmailNew = '" & Replace(newEmailNew, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">EmailNew updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating EmailNew.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldEmailNew & "</td>")
                                                                End If

                                                                If newEmailAssign <> oldEmailAssign Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldEmailAssign & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_EmailAssign = '" & Replace(newEmailAssign, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">EmailAssign updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating EmailAssign.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldEmailAssign & "</td>")
                                                                End If

                                                                If newEmailStatus <> oldEmailStatus Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldEmailStatus & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_EmailStatus = '" & Replace(newEmailStatus, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">EmailStatus updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating EmailStatus.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldEmailStatus & "</td>")
                                                                End If

                                                                If newShowOn <> oldShowOn Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldShowOn & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_ShowOn = '" & Replace(newShowOn, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">ShowOn updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating ShowOn.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldShowOn & "</td>")
                                                                End If

                                                                If newActive <> oldActive Then
                                                                    Response_WriteLine("<td><font color=""green""><b>" & oldActive & "</b></font></td>")
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Active = '" & newActive & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">Active updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Active.</font><br>"
                                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If

                                                                    ' BONUS - check this member's tab_Messages.Msg_Assigned field to see if Inactivating a member with open messages
                                                                    ' This is STRICTLY a check for when toggling Active.
                                                                    ' search Messages for new username as Find/Replace was already done.
                                                                    If newActive = "No" Then
                                                                        sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(newUsername, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & oldTeamIndex & " AND tab_Messages.Msg_Completed IS NULL;"

                                                                        MyCommand3.CommandText = sSqlString

                                                                        Try
                                                                            If MyConnection3.State = ConnectionState.Closed Then
                                                                                MyConnection3.Open()
                                                                            End If

                                                                            sqlDataReader3 = MyCommand3.ExecuteReader

                                                                            If sqlDataReader3.Read = True Then
                                                                                thecount = sqlDataReader3.Item("THECOUNT")

                                                                                If thecount > 0 Then
                                                                                    ' Found one or more
                                                                                    EXTRAMSG = EXTRAMSG & "<table><tr><td><font color=""red"">"
                                                                                    EXTRAMSG = EXTRAMSG & "Note - Username found in " & thecount & " Open assigned Team Message(s).<br>"
                                                                                    EXTRAMSG = EXTRAMSG & "Suggestion - reassign those messages to another <b><i>Active</i></b> "
                                                                                    EXTRAMSG = EXTRAMSG & "Team Member for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>."
                                                                                    EXTRAMSG = EXTRAMSG & "</font></td></tr></table>"
                                                                                Else
                                                                                    EXTRAMSG = EXTRAMSG & "<font color=""navy"">Note - Username not found in Assigned Messages for Team <i>"
                                                                                    EXTRAMSG = EXTRAMSG & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</i>,<br>"
                                                                                    EXTRAMSG = EXTRAMSG & "nothing to reassign due to <b><i>deactivating</i></b> " & form_Username & ".</font><br>"
                                                                                End If
                                                                            End If

                                                                        Catch ex As Exception
                                                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                                        Finally
                                                                            If MyConnection3.State = ConnectionState.Open Then MyConnection3.Close()
                                                                            If (Not sqlDataReader3 Is Nothing) Then sqlDataReader3.Close()
                                                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                                        End Try

                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldActive & "</td>")
                                                                End If

                                                                If newNotes <> oldNotes Then
                                                                    ' old Notes potentially was NULL vlaue
                                                                    If oldNotes = "" Then
                                                                        Response_WriteLine("<td>&nbsp;</td>")
                                                                    Else
                                                                        Response_WriteLine("<td><font color=""green""><b>" & oldNotes & "</b></font></td>")
                                                                    End If
                                                                    UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Notes = '" & Replace(newNotes, "'", "''") & "' WHERE tab_Members.Me_Index = " & oldIndex & ";")
                                                                    'On Error Resume Next
                                                                    If Err.Number = 0 Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""green"">Notes updated successfully.</font><br>"
                                                                    Else
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">ERROR updating Notes.</font><br>"
                                                                    End If
                                                                    'On Error GoTo 0

                                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                    errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                    If errstore <> "Success" Then
                                                                        EXTRAMSG = EXTRAMSG & "<font color=""red"">" & errstore & "</font><br>"
                                                                    End If
                                                                Else
                                                                    Response_WriteLine("<td>" & oldNotes & "</td>")
                                                                End If
                                                                Response_WriteLine("</tr>")
                                                            Else
                                                                ' not checked, skip it
                                                                Response_WriteLine("<tr valign=""top"">")
                                                                Response_WriteLine("<td>Skipping:</td>")
                                                                Response_WriteLine("<td>" & Me.GetLocationName(Me.GetLocationIndex(oldTeamIndex)) & " - " & Me.GetTeamName(oldTeamIndex) & "</td>")
                                                                Response_WriteLine("<td>" & oldUsername & "</td>")
                                                                Response_WriteLine("<td>" & oldSID & "</td>")
                                                                Response_WriteLine("<td>" & oldName & "</td>")
                                                                Response_WriteLine("<td>" & oldTitle & "</td>")
                                                                Response_WriteLine("<td>" & oldEmail & "</td>")
                                                                Response_WriteLine("<td>" & oldEmailNew & "</td>")
                                                                Response_WriteLine("<td>" & oldEmailAssign & "</td>")
                                                                Response_WriteLine("<td>" & oldEmailStatus & "</td>")
                                                                Response_WriteLine("<td>" & oldShowOn & "</td>")
                                                                Response_WriteLine("<td>" & oldActive & "</td>")
                                                                Response_WriteLine("<td>" & oldNotes & "</td>")
                                                                Response_WriteLine("</tr>")
                                                            End If
                                                        End While
                                                        Response_WriteLine("</table>")
                                                        Response_WriteLine("</p>")
                                                        If EXTRAMSG <> "" Then
                                                            Response_WriteLine("<p><table><tr><td>")
                                                            Response_WriteLine("<hr color=""black"">")
                                                            Response_WriteLine("" & EXTRAMSG & "")
                                                            Response_WriteLine("<hr color=""black"">")
                                                            Response_WriteLine("</td></tr></table></p>")
                                                        Else
                                                            Response_WriteLine("<p><b><font color=""green"">Nothing adjusted!</font></b></p>")
                                                        End If
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        ' now show some shortcut editing links to assist in hopping to another user
                                        Response_WriteLine("<p>Return to the <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a> menu.</p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<table cellspacing=""0"">")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Choose Another Related Edit option?</th></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td>")
                                        Response_WriteLine("<td colspan=""2""><b>" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & "</b>")
                                        Response_WriteLine("<form name=""frmLinkEditSiteFromEM2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromEM2.submit()""><small>Edit</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Location</b>&nbsp;</td>")
                                        Response_WriteLine("<td colspan=""2""><b>" & Me.GetLocationName(form_LocationIndex) & "</b>")
                                        Response_WriteLine("<form name=""frmLinkEditLocationFromEM2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromEM2.submit()""><small>Edit</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Team</b>&nbsp;</td>")
                                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                            Response_WriteLine("<td colspan=""2""><b>" & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</b>")
                                        Else
                                            Response_WriteLine("<td colspan=""2""><b>" & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</b>")
                                        End If
                                        Response_WriteLine("<form name=""frmLinkEditTeamFromEM2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditTeamFromEM2.submit()""><small>Edit</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        ' check for Nothing list, highlight this member's NewName in the list.  It *must* exist there.
                                        tempNames = Me.GetTeamMemberNames(form_TeamIndex, True, True)
                                        If tempNames = "" Then
                                            tempNames = "<font color=""red"">No Members Exist Yet</font>"
                                        Else
                                            tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                            ' tempNames has the title within it, so match strictly the NewName
                                            tempNames = Replace(tempNames, newName, "<b>" & newName & "</b>")
                                        End If
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Team&nbsp;Members&nbsp;</td>")
                                        Response_WriteLine("<td colspan=""2"">" & tempNames & "")
                                        Response_WriteLine("<br>")
                                        Response_WriteLine("<form name=""frmLinkAddMemberFromEM2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                        Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddMemberFromEM2.submit()""><small>Add Member</small></a>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</td></tr>")
                                        ' highlight this member's email in the TeamEmail, if it exists in there...
                                        tempEmail = Me.GetTeamMemberNewEmails(form_TeamIndex)
                                        If tempEmail = "" Then
                                            tempEmail = "<font color=""red"">No Email Recipients for New Messages</font>"
                                        Else
                                            tempEmail = LCase(tempEmail)
                                            ' can't be any subset duplicate email matches, no need to match the <form tag too
                                            tempEmail = Replace(tempEmail, LCase(newEmail), "<b>" & LCase(newEmail) & "</b>")
                                        End If
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</td></tr></table>")
                                    Case Else

                                        If form_Method = "StoreMe" Then
                                            ' new EditMember fields submitted, store them

                                            form_Error = ""
                                            ' TeamIndex is not editable
                                            ' form_MemberIndex is guaranteed to have a value
                                            ' form_SortOrder is guaranteed to have a value
                                            If form_Name = "" Then
                                                form_Error = form_Error & " Name"
                                            End If
                                            If form_Title = "" Then
                                                form_Error = form_Error & " Title"
                                            End If
                                            If form_Username = "" Then
                                                form_Error = form_Error & " Username"
                                            Else
                                                If InStr(form_Username, "\") Then
                                                    ' good, has "\" in the value
                                                Else
                                                    ' Missing Valid-Domain\Username
                                                    form_Error = form_Error & " Valid-Domain\Username"
                                                End If
                                            End If
                                            If form_SID = "" Then
                                                form_Error = form_Error & " SID"
                                            End If
                                            If form_Email = "" Then
                                                form_Error = form_Error & " Email"
                                            Else
                                                If Not Me.isValidEmail(form_Email) Then
                                                    ' Missing Valid-Email
                                                    form_Error = form_Error & "Valid-Email"
                                                End If
                                            End If
                                            ' form_EmailNew = guaranteed "Yes" or "No"
                                            ' form_EmailAssign = guaranteed "Yes" or "No"
                                            ' form_EmailStatus = guaranteed "Yes" or "No"
                                            ' form_ShowOn = guaranteed "Yes" or "No"
                                            ' form_Active = guaranteed "Yes" or "No"
                                            If form_Notes = "" Then
                                                form_Error = form_Error & " Notes"
                                            End If
                                            Response_WriteLine("<p>")
                                            If form_Error = "" Then
                                                ' safe to update

                                                sSqlString = "SELECT * FROM tab_Members WHERE tab_Members.Me_Index = " & form_MemberIndex & ";"

                                                MyCommand.CommandText = sSqlString

                                                Try
                                                    If MyConnection.State = ConnectionState.Closed Then
                                                        MyConnection.Open()
                                                    End If

                                                    sqlDataReader = MyCommand.ExecuteReader

                                                    If Not sqlDataReader.Read Then
                                                        Response_WriteLine("<font color=""red"">Error - " & form_MemberIndexe & " not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font><br>")
                                                    Else
                                                        ' store as a variable for reference
                                                        form_TeamIndex = sqlDataReader.Item("Me_TeamIndex")

                                                        ' load original values for later reference
                                                        oldSortOrder = sqlDataReader.Item("Me_SortOrder")
                                                        oldUsername = sqlDataReader.Item("Me_Username")
                                                        oldName = sqlDataReader.Item("Me_Name")
                                                        oldTitle = sqlDataReader.Item("Me_Title")
                                                        oldEmail = sqlDataReader.Item("Me_Email")
                                                        oldEmailNew = sqlDataReader.Item("Me_EmailNew")
                                                        oldEmailAssign = sqlDataReader.Item("Me_EmailAssign")
                                                        oldEmailStatus = sqlDataReader.Item("Me_EmailStatus")
                                                        oldShowOn = sqlDataReader.Item("Me_ShowOn")
                                                        oldActive = sqlDataReader.Item("Me_Active")
                                                        oldSID = sqlDataReader.Item("Me_SID")
                                                        oldNotes = sqlDataReader.Item("Me_Notes")

                                                        ' most fields are guaranteed not to be NULL, but converting to "" just in case
                                                        ' old Title could be a NULL value before it became required
                                                        ' old SID could be a NULL value before it became required
                                                        ' old Notes could be a NULL value before it became required
                                                        If IsDBNull(oldUsername) Then oldUsername = ""
                                                        If IsDBNull(oldName) Then oldName = ""
                                                        If IsDBNull(oldTitle) Then oldTitle = ""
                                                        If IsDBNull(oldEmail) Then oldEmail = ""
                                                        If IsDBNull(oldEmailNew) Then oldEmailNew = ""
                                                        If IsDBNull(oldEmailAssign) Then oldEmailAssign = ""
                                                        If IsDBNull(oldEmailStatus) Then oldEmailStatus = ""
                                                        If IsDBNull(oldShowOn) Then oldShowOn = ""
                                                        If IsDBNull(oldActive) Then oldActive = ""
                                                        If IsDBNull(oldSID) Then oldSID = ""
                                                        If IsDBNull(oldNotes) Then oldNotes = ""

                                                        ' store new sort order
                                                        If CStr(oldSortOrder) <> Replace(form_SortOrder, "AAA", "") Then
                                                            Me.ReSortMember(form_MemberIndex, form_SortOrder)

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", "Sort Order changed to " & form_SortOrder & " for Index = " & form_MemberIndex)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldName <> form_Name Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">Name updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating Name.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldTitle <> form_Title Then
                                                            ' form field valid so store updated title
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Title = '" & Replace(form_Title, "'", "''") & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">Title updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating Title.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        End If

                                                        ' first convert to Uppercase
                                                        form_Username = UCase(form_Username)
                                                        If oldUsername <> form_Username Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Username = '" & Replace(form_Username, "'", "''") & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">Username updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating Username.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If

                                                            ' BONUS - check this member's tab_Messages.Msg_Assigned field for OPEN messages to see if that now needs adjusting
                                                            sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(oldUsername, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & form_TeamIndex & " AND tab_Messages.Msg_Completed IS NULL;"

                                                            MyCommand2.CommandText = sSqlString

                                                            Try
                                                                If MyConnection2.State = ConnectionState.Closed Then
                                                                    MyConnection2.Open()
                                                                End If

                                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                                If sqlDataReader2.Read = True Then
                                                                    thecount = sqlDataReader2.Item("THECOUNT")

                                                                    If thecount > 0 Then
                                                                        ' Found one
                                                                        UpdateTableRecord("UPDATE tab_Messages SET tab_Messages.Msg_Assigned = '" & Replace(form_Username, "'", "''") & "'" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(oldUsername, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & form_TeamIndex & " AND tab_Messages.Msg_Completed IS NULL;")
                                                                        'On Error Resume Next
                                                                        If Err.Number = 0 Then
                                                                            Response_WriteLine("<table><tr><td><font color=""navy"">")
                                                                            Response_WriteLine("Note - Old Username found in " & thecount & " assigned Open Message(s).<br>")
                                                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                                Response_WriteLine("Replaced username for " & thecount & " assigned Open Messages for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</i>.")
                                                                            Else
                                                                                Response_WriteLine("Replaced username for " & thecount & " assigned Open Messages for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</i>.")
                                                                            End If
                                                                            Response_WriteLine("</font></td></tr></table>")
                                                                        Else
                                                                            Response_WriteLine("<font color=""red"">ERROR updating Open Messages assigned to old username <i>" & oldUsername & "</i> with new username <i>" & form_Username & "</i> for ")
                                                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                                Response_WriteLine("Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</i>.</font><br>")
                                                                            Else
                                                                                Response_WriteLine("Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</i>.</font><br>")
                                                                            End If
                                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                                        End If
                                                                        'On Error GoTo 0

                                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                                        errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                                        If errstore <> "Success" Then
                                                                            Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                                        End If
                                                                    Else
                                                                        If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                            Response_WriteLine("<font color=""navy"">Note - Old Username not found in Assigned Open Messages for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</i>, nothing to auto-correct.</font><br>")
                                                                        Else
                                                                            Response_WriteLine("<font color=""navy"">Note - Old Username not found in Assigned Open Messages for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</i>, nothing to auto-correct.</font><br>")
                                                                        End If
                                                                    End If
                                                                End If

                                                            Catch ex As Exception
                                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                            Finally
                                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                            End Try

                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldSID <> form_SID Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_SID = '" & form_SID & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">SID updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating SID.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        ' first convert to Lowercase
                                                        form_Email = LCase(form_Email)
                                                        If oldEmail <> form_Email Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Email = '" & Replace(form_Email, "'", "''") & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">Email updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating Email.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldEmailNew <> form_EmailNew Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_EmailNew = '" & form_EmailNew & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">EmailNew updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating EmailNew.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldEmailAssign <> form_EmailAssign Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_EmailAssign = '" & form_EmailAssign & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">EmailAssign updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating EmailAssign.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldEmailStatus <> form_EmailStatus Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_EmailStatus = '" & form_EmailStatus & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">EmailStatus updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating EmailStatus.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldShowOn <> form_ShowOn Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_ShowOn = '" & form_ShowOn & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">ShowOn updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating ShowOn.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldActive <> form_Active Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Active = '" & form_Active & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">Active updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating Active.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If

                                                            ' BONUS - check this member's tab_Messages.Msg_Assigned field to see if Inactivating a member with open messages
                                                            ' This is STRICTLY a check for when toggling Active to "No"
                                                            ' search Messages for new username as Find/Replace was already done.
                                                            If form_Active = "No" Then
                                                                ' search Messages for new username as Find/Replace was already done.
                                                                sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(form_Username, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & form_TeamIndex & " AND tab_Messages.Msg_Completed IS NULL;"

                                                                MyCommand2.CommandText = sSqlString

                                                                Try
                                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                                        MyConnection2.Open()
                                                                    End If

                                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                                    If sqlDataReader2.Read = True Then
                                                                        thecount = sqlDataReader2.Item("THECOUNT")

                                                                        If thecount > 0 Then
                                                                            ' Found one or more
                                                                            Response_WriteLine("<table><tr><td><font color=""red"">")
                                                                            Response_WriteLine("Note - Username found in " & thecount & " Assigned Open Message(s).<br>")
                                                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                                Response_WriteLine("Suggestion - reassign those messages to another <b><i>Active</i></b> Team Member for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</i>.")
                                                                            Else
                                                                                Response_WriteLine("Suggestion - reassign those messages to another <b><i>Active</i></b> Team Member for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</i>.")
                                                                            End If
                                                                            Response_WriteLine("</font></td></tr></table>")
                                                                        Else
                                                                            If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                                Response_WriteLine("<font color=""navy"">Note - Username not found in Assigned Open Messages for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</i>,<br>")
                                                                            Else
                                                                                Response_WriteLine("<font color=""navy"">Note - Username not found in Assigned Open Messages for Team <i>" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</i>,<br>")
                                                                            End If
                                                                            Response_WriteLine("nothing to reassign due to <b><i>deactivating</i></b> " & form_Username & ".</font><br>")
                                                                        End If
                                                                    End If

                                                                Catch ex As Exception
                                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                                Finally
                                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                                End Try

                                                            Else
                                                                ' turned to "Yes", don't need to check for open assigned messgaes
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        If oldNotes <> form_Notes Then
                                                            UpdateTableRecord("UPDATE tab_Members SET tab_Members.Me_Notes = '" & Replace(form_Notes, "'", "''") & "' WHERE tab_Members.Me_Index = " & form_MemberIndex & ";")
                                                            'On Error Resume Next
                                                            If Err.Number = 0 Then
                                                                Response_WriteLine("<font color=""green"">Notes updated successfully.</font><br>")
                                                            Else
                                                                Response_WriteLine("<font color=""red"">ERROR updating Notes.</font><br>")
                                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                            End If
                                                            'On Error GoTo 0

                                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                                            errstore = Me.StoreAuditAdmin("Edit Member", sSqlString)
                                                            If errstore <> "Success" Then
                                                                Response_WriteLine("<font color=""red"">" & errstore & "</font><br>")
                                                            End If
                                                        Else
                                                            ' skip, not changed
                                                        End If

                                                        ' BONUS - check this username to see if member of other teams.
                                                        ' If so, offer to change Username, Email, Name, Title, EmailNew, EmailAssign, EmailStatus, ShowOn, Active fields. 
                                                        sSqlString = "SELECT * FROM tab_Members WHERE tab_Members.Me_Username LIKE '" & Replace(oldUsername, "'", "''") & "'" & " AND tab_Members.Me_Index <> " & form_MemberIndex & ";"

                                                        MyCommand2.CommandText = sSqlString

                                                        Try
                                                            If MyConnection2.State = ConnectionState.Closed Then
                                                                MyConnection2.Open()
                                                            End If

                                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                                            If Not sqlDataReader2.HasRows Then
                                                                Response_WriteLine("<font color=""navy"">Note - Username not found in other Teams, nothing to automatically update.</font><br>")
                                                            Else
                                                                ' pass in form:
                                                                '    form_Username = oldUserName - to find all the other matching teams to loop through
                                                                '    form_MemberIndex = MemberIndex - source data to use for each field to update in the loop
                                                                '    form_Check_nnnn = nnnn - target Member Index - checked = "Yes" or checked = "No"

                                                                ' load LocationIndex to be used after submitting
                                                                form_LocationIndex = Me.GetLocationIndex(sqlDataReader.Item("Me_TeamIndex"))
                                                                ' load SiteNum to be used after submitting
                                                                form_SiteNum = Me.GetSiteNum(form_LocationIndex)
                                                                Response_WriteLine("<br>")
                                                                Response_WriteLine("<table bordercolor=""black"" cellpadding=""0"" cellspacing=""0"" border=""1""><tr><td>")
                                                                Response_WriteLine("<form name=""frmMethodEditMemberMultiple"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_MemberIndex"" value=""" & form_MemberIndex & """>")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & oldUsername & """>")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""ChoseAD"">")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                                                Response_WriteLine("<table>")
                                                                Response_WriteLine("<tr><td colspan=""13""><center>")
                                                                Response_WriteLine("<font color=red>" & oldUsername & "</font> exists in multiple teams<br>")
                                                                Response_WriteLine("<br>")
                                                                Response_WriteLine("<table bgcolor=""#eeeeee""  border=""1"" bordercolor=""#d6dbe9"" cellspacing=""0"" cellpadding=""5""><tr><td>")
                                                                Response_WriteLine("To update other teams<br>")
                                                                Response_WriteLine("1. Check the box in the ""Change?"" column.<br>")
                                                                Response_WriteLine("2. Click the button ""Change Checked Fields Too""<br>")
                                                                Response_WriteLine("* All fields on destination team will be  to match *<br>")
                                                                Response_WriteLine("</td></tr></table>")
                                                                Response_WriteLine("</center></td></tr>")
                                                                Response_WriteLine("<tr><th colspan=""13""><br>Changes to THIS Team</th></tr>")
                                                                Response_WriteLine("<tr bgcolor=""#d6dbe9"">")
                                                                Response_WriteLine("<th bgcolor=""white"">&nbsp;</th>")
                                                                Response_WriteLine("<th bgcolor=""#eeeeee"">Team</th>")
                                                                Response_WriteLine("<th>Username</th>")
                                                                Response_WriteLine("<th>SID</th>")
                                                                Response_WriteLine("<th>Name</th>")
                                                                Response_WriteLine("<th>Title</th>")
                                                                Response_WriteLine("<th>Email</th>")
                                                                Response_WriteLine("<th>E-New</th>")
                                                                Response_WriteLine("<th>E-Assign</th>")
                                                                Response_WriteLine("<th>E-Status</th>")
                                                                Response_WriteLine("<th>Show</th>")
                                                                Response_WriteLine("<th>Active</th>")
                                                                Response_WriteLine("<th>Notes</th>")
                                                                Response_WriteLine("</tr>")
                                                                Response_WriteLine("<tr valign=""top"">")
                                                                Response_WriteLine("<th bgcolor=""#eeeeee"">Original</th>")
                                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</td>")
                                                                Else
                                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</td>")
                                                                End If
                                                                Response_WriteLine("<td>" & oldUsername & "</td>")
                                                                Response_WriteLine("<td>" & oldSID & "</td>")
                                                                Response_WriteLine("<td>" & oldName & "</td>")
                                                                Response_WriteLine("<td>" & oldTitle & "</td>")
                                                                Response_WriteLine("<td>" & oldEmail & "</td>")
                                                                Response_WriteLine("<td>" & oldEmailNew & "</td>")
                                                                Response_WriteLine("<td>" & oldEmailAssign & "</td>")
                                                                Response_WriteLine("<td>" & oldEmailStatus & "</td>")
                                                                Response_WriteLine("<td>" & oldShowOn & "</td>")
                                                                Response_WriteLine("<td>" & oldActive & "</td>")
                                                                Response_WriteLine("<td>" & oldNotes & "</td>")
                                                                Response_WriteLine("</tr>")
                                                                Response_WriteLine("<tr valign=""top"">")
                                                                Response_WriteLine("<th bgcolor=""#eeeeee"">Updated</th>")
                                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & "</td>")
                                                                Else
                                                                    Response_WriteLine("<td bgcolor=""#eeeeee"">" & Me.GetLocationName(Me.GetLocationIndex(form_TeamIndex)) & " - " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & "</td>")
                                                                End If
                                                                If form_Username <> oldUsername Then
                                                                    Response_WriteLine("<td><font color=green>" & form_Username & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_Username & "</td>")
                                                                End If
                                                                If form_SID <> oldSID Then
                                                                    Response_WriteLine("<td><font color=green>" & form_SID & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_SID & "</td>")
                                                                End If
                                                                If form_Name <> oldName Then
                                                                    Response_WriteLine("<td><font color=green>" & form_Name & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_Name & "</td>")
                                                                End If
                                                                If form_Title <> oldTitle Then
                                                                    Response_WriteLine("<td><font color=green>" & form_Title & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_Title & "</td>")
                                                                End If
                                                                If form_Email <> oldEmail Then
                                                                    Response_WriteLine("<td><font color=green>" & form_Email & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_Email & "</td>")
                                                                End If
                                                                If form_EmailNew <> oldEmailNew Then
                                                                    Response_WriteLine("<td><font color=green>" & form_EmailNew & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_EmailNew & "</td>")
                                                                End If
                                                                If form_EmailAssign <> oldEmailAssign Then
                                                                    Response_WriteLine("<td><font color=green>" & form_EmailAssign & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_EmailAssign & "</td>")
                                                                End If
                                                                If form_EmailStatus <> oldEmailStatus Then
                                                                    Response_WriteLine("<td><font color=green>" & form_EmailStatus & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_EmailStatus & "</td>")
                                                                End If
                                                                If form_ShowOn <> oldShowOn Then
                                                                    Response_WriteLine("<td><font color=green>" & form_ShowOn & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_ShowOn & "</td>")
                                                                End If
                                                                If form_Active <> oldActive Then
                                                                    Response_WriteLine("<td><font color=green>" & form_Active & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_Active & "</td>")
                                                                End If
                                                                If form_Notes <> oldNotes Then
                                                                    Response_WriteLine("<td><font color=green>" & form_Notes & "</font></td>")
                                                                Else
                                                                    Response_WriteLine("<td>" & form_Notes & "</td>")
                                                                End If
                                                                Response_WriteLine("</tr>")
                                                                Response_WriteLine("<tr><th colspan=""13""><br>Differences in OTHER Teams</th></tr>")
                                                                Response_WriteLine("<tr bgcolor=""#d6dbe9"">")
                                                                Response_WriteLine("<th bgcolor=""#d6dbe9"">Change?</th>")
                                                                Response_WriteLine("<th bgcolor=""#eeeeee"">Team</th>")
                                                                Response_WriteLine("<th>Username</th>")
                                                                Response_WriteLine("<th>SID</th>")
                                                                Response_WriteLine("<th>Name</th>")
                                                                Response_WriteLine("<th>Title</th>")
                                                                Response_WriteLine("<th>Email</th>")
                                                                Response_WriteLine("<th>E-New</th>")
                                                                Response_WriteLine("<th>E-Assign</th>")
                                                                Response_WriteLine("<th>E-Status</th>")
                                                                Response_WriteLine("<th>Show</th>")
                                                                Response_WriteLine("<th>Active</th>")
                                                                Response_WriteLine("<th>Notes</th>")
                                                                Response_WriteLine("</tr>")
                                                                While sqlDataReader2.Read = True
                                                                    newUsername = sqlDataReader2.Item("Me_Username")
                                                                    newName = sqlDataReader2.Item("Me_Name")
                                                                    newTitle = sqlDataReader2.Item("Me_Title")
                                                                    newEmail = sqlDataReader2.Item("Me_Email")
                                                                    newEmailNew = sqlDataReader2.Item("Me_EmailNew")
                                                                    newEmailAssign = sqlDataReader2.Item("Me_EmailAssign")
                                                                    newEmailStatus = sqlDataReader2.Item("Me_EmailStatus")
                                                                    newShowOn = sqlDataReader2.Item("Me_ShowOn")
                                                                    newActive = sqlDataReader2.Item("Me_Active")
                                                                    newSID = sqlDataReader2.Item("Me_SID")
                                                                    newNotes = sqlDataReader2.Item("Me_Notes")
                                                                    If IsDBNull(newUsername) Then newUsername = ""
                                                                    If IsDBNull(newName) Then newName = ""
                                                                    If IsDBNull(newTitle) Then newTitle = ""
                                                                    If IsDBNull(newEmail) Then newEmail = ""
                                                                    If IsDBNull(newEmailNew) Then newEmailNew = ""
                                                                    If IsDBNull(newEmailAssign) Then newEmailAssign = ""
                                                                    If IsDBNull(newEmailStatus) Then newEmailStatus = ""
                                                                    If IsDBNull(newShowOn) Then newShowOn = ""
                                                                    If IsDBNull(newActive) Then newActive = ""
                                                                    If IsDBNull(newSID) Then newSID = ""
                                                                    If IsDBNull(newNotes) Then newNotes = ""
                                                                    Response_WriteLine("<tr valign=""top"">")
                                                                    Response_WriteLine("<td bgcolor=""#d6dbe9"" align=""center""><div class=""checkbox""><label><input type=""checkbox"" name=""form_Check_" & sqlDataReader2.Item("Me_Index") & """></label></div></td>")
                                                                    If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">" & Me.GetLocationName(Me.GetLocationIndex(sqlDataReader2.Item("Me_TeamIndex"))) & " - " & Me.ColorizeTeamName(Me.GetTeamName(sqlDataReader2.Item("Me_TeamIndex"))) & "</td>")
                                                                    Else
                                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">" & Me.GetLocationName(Me.GetLocationIndex(sqlDataReader2.Item("Me_TeamIndex"))) & " - " & Me.ColorizeFont(Me.GetTeamName(sqlDataReader2.Item("Me_TeamIndex"))) & "</td>")
                                                                    End If
                                                                    If form_Username <> newUsername Then
                                                                        Response_WriteLine("<td><font color=red>" & newUsername & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newUsername & "</td>")
                                                                    End If
                                                                    If form_SID <> newSID Then
                                                                        Response_WriteLine("<td><font color=red>" & newSID & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newSID & "</td>")
                                                                    End If
                                                                    If form_Name <> newName Then
                                                                        Response_WriteLine("<td><font color=red>" & newName & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newName & "</td>")
                                                                    End If
                                                                    If form_Title <> newTitle Then
                                                                        Response_WriteLine("<td><font color=red>" & newTitle & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newTitle & "</td>")
                                                                    End If
                                                                    If form_Email <> newEmail Then
                                                                        Response_WriteLine("<td><font color=red>" & newEmail & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newEmail & "</td>")
                                                                    End If
                                                                    If form_EmailNew <> newEmailNew Then
                                                                        Response_WriteLine("<td><font color=red>" & newEmailNew & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newEmailNew & "</td>")
                                                                    End If
                                                                    If form_EmailAssign <> newEmailAssign Then
                                                                        Response_WriteLine("<td><font color=red>" & newEmailAssign & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newEmailAssign & "</td>")
                                                                    End If
                                                                    If form_EmailStatus <> newEmailStatus Then
                                                                        Response_WriteLine("<td><font color=red>" & newEmailStatus & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newEmailStatus & "</td>")
                                                                    End If
                                                                    If form_ShowOn <> newShowOn Then
                                                                        Response_WriteLine("<td><font color=red>" & newShowOn & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newShowOn & "</td>")
                                                                    End If
                                                                    If form_Active <> newActive Then
                                                                        Response_WriteLine("<td><font color=red>" & newActive & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newActive & "</td>")
                                                                    End If
                                                                    If form_Notes <> newNotes Then
                                                                        Response_WriteLine("<td><font color=red>" & newNotes & "</font></td>")
                                                                    Else
                                                                        Response_WriteLine("<td>" & newNotes & "</td>")
                                                                    End If
                                                                    Response_WriteLine("</tr>")
                                                                End While
                                                                Response_WriteLine("<tr><td colspan=""13"">")
                                                                Response_WriteLine("<center>")
                                                                Response_WriteLine("<br>")
                                                                Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Change Checked Fields Too"">")
                                                                Response_WriteLine("<br>")
                                                                Response_WriteLine("<br>")
                                                                Response_WriteLine("</center>")
                                                                Response_WriteLine("</td></tr></table>")
                                                                Response_WriteLine("</form>")
                                                                Response_WriteLine("</td></tr></table>")
                                                                Response_WriteLine("<br>")
                                                            End If

                                                        Catch ex As Exception
                                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                        Finally
                                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                        End Try

                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                            Else
                                                ' missing info, try again
                                                Response_WriteLine("<font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font><br>")
                                            End If
                                            Response_WriteLine("</p>")
                                        End If  ' form_Method = "StoreMe"

                                        ' SHOW Edit Member Form '

                                        ' get MemberIndex for form entry with Username and TeamIndex
                                        If form_MemberIndex = "0" And (Not IsNothing(form_Username)) And (Not IsNothing(form_TeamIndex)) Then
                                            sSqlString = "SELECT tab_Members.Me_Index FROM tab_Members" & " WHERE tab_Members.Me_Username LIKE '" & form_Username & "'" & " AND tab_Members.Me_TeamIndex = " & form_TeamIndex & ";"

                                            MyCommand.CommandText = sSqlString

                                            Try
                                                If MyConnection.State = ConnectionState.Closed Then
                                                    MyConnection.Open()
                                                End If

                                                sqlDataReader = MyCommand.ExecuteReader

                                                If sqlDataReader.Read = True Then
                                                    form_MemberIndex = sqlDataReader.Item("Me_Index")
                                                    form_MemberIndex = CStr(form_MemberIndex)
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                        End If

                                        ' reload rs with the new edited values
                                        sSqlString = "SELECT * FROM tab_Members WHERE tab_Members.Me_Index = " & form_MemberIndex & ";"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Member, """ & form_MemberIndex & """ not found in database.</font></p>")
                                            Else
                                                ' either first time in, or name chosen/cancelled from AD
                                                If form_Method = "ChoseAD" Then
                                                    ' ADFULL not used, regenerate without middle initial and in "First Last" form
                                                    If ADloop = "x" Or ADloop = "" Then
                                                        ' x means cancel clicked, use the previously typed in value still
                                                        ADFULL = Request.Form("ADFULLx")
                                                        ADE = Request.Form("ADEx")
                                                        ADU = Request.Form("ADUx")
                                                        ADSID = Request.Form("ADSIDx")
                                                        ADT = Request.Form("ADTx")
                                                    Else
                                                        ' AD form used, name selected, load First, Last and Email
                                                        ADF = Request.Form("ADF" & ADloop)
                                                        ADL = Request.Form("ADL" & ADloop)
                                                        ADE = Request.Form("ADE" & ADloop)
                                                        ' Title shown for reference here, not used in form field though
                                                        ADT = Request.Form("ADT" & ADloop)
                                                        ADT = Replace(ADT, "EXEMPT: ", "")
                                                        ADU = Request.Form("ADU" & ADloop)
                                                        ADSID = Request.Form("ADSID" & ADloop)

                                                        ' ADFULL not used from AD's DisplayName.
                                                        ' generate instead, using "first last" notation
                                                        ' ADFULL = Request.Form("ADFULL" & ADloop)
                                                        ADFULL = ADF & " " & ADL
                                                        If ADFULL = " " Then
                                                            ADFULL = ""
                                                        End If
                                                    End If
                                                Else
                                                    ' first time into AD search, use the existing database values still
                                                    ADFULL = sqlDataReader.Item("Me_Name")
                                                    ADU = sqlDataReader.Item("Me_Username")
                                                    ADE = sqlDataReader.Item("Me_Email")
                                                    ADSID = sqlDataReader.Item("Me_SID")
                                                    ADT = sqlDataReader.Item("Me_Title")
                                                    If IsDBNull(ADFULL) Then ADFULL = ""
                                                    If IsDBNull(ADU) Then ADU = ""
                                                    If IsDBNull(ADE) Then ADE = ""
                                                    If IsDBNull(ADSID) Then ADSID = ""
                                                    If IsDBNull(ADT) Then ADT = ""
                                                End If
                                                ADU = UCase(ADU)
                                                ADE = LCase(ADE)

                                                ' use FORM values in case they were adjusted prior to clicking LookUp
                                                If form_SortOrder = "" Then
                                                    form_SortOrder = sqlDataReader.Item("Me_SortOrder")
                                                    If IsDBNull(form_SortOrder) Then form_SortOrder = ""
                                                End If
                                                If form_EmailNew = "" Then
                                                    form_EmailNew = sqlDataReader.Item("Me_EmailNew")
                                                    If IsDBNull(form_EmailNew) Then form_EmailNew = ""
                                                End If
                                                If form_EmailAssign = "" Then
                                                    form_EmailAssign = sqlDataReader.Item("Me_EmailAssign")
                                                    If IsDBNull(form_EmailAssign) Then form_EmailAssign = ""
                                                End If
                                                If form_EmailStatus = "" Then
                                                    form_EmailStatus = sqlDataReader.Item("Me_EmailStatus")
                                                    If IsDBNull(form_EmailStatus) Then form_EmailStatus = ""
                                                End If
                                                If form_ShowOn = "" Then
                                                    form_ShowOn = sqlDataReader.Item("Me_ShowOn")
                                                    If IsDBNull(form_ShowOn) Then form_ShowOn = ""
                                                End If
                                                If form_Active = "" Then
                                                    form_Active = sqlDataReader.Item("Me_Active")
                                                    If IsDBNull(form_Active) Then form_Active = ""
                                                End If
                                                If form_Notes = "" Then
                                                    form_Notes = sqlDataReader.Item("Me_Notes")
                                                    If IsDBNull(form_Notes) Then
                                                        form_Notes = "Edit by " & Me.UserName & " on " & theDate
                                                    End If
                                                End If

                                                ' load Username to be used after this table - with the ShowMembersTable routine call
                                                form_Username = sqlDataReader.Item("Me_Username")
                                                ' load LocationIndex to be used in and after this table - with the ShowTeamsTable routine call
                                                form_LocationIndex = Me.GetLocationIndex(sqlDataReader.Item("Me_TeamIndex"))
                                                ' load SiteNum to be used in forms
                                                form_SiteNum = Me.GetSiteNum(form_LocationIndex)

                                                If IsDBNull(sqlDataReader.Item("Me_Notes")) Then
                                                    memoNotes = "Edit by " & Me.UserName & " on " & theDate
                                                Else
                                                    memoNotes = sqlDataReader.Item("Me_Notes")
                                                End If
                                                Response_WriteLine("<p>")
                                                Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                                Response_WriteLine("<table cellspacing=""0"">")
                                                Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit a Member</th></tr>")
                                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td align=""right""><b>Index</b>&nbsp;</td><td colspan=""2""><b>" & form_MemberIndex & "</b></td></tr>")
                                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Site</b>&nbsp;</td>")
                                                Response_WriteLine("<td colspan=""2""><b>" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & "</b>")
                                                Response_WriteLine("<form name=""frmLinkEditSiteFromEM"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditSiteFromEM.submit()""><small>Edit</small></a>")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                                Response_WriteLine("</form>")
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Location</b>&nbsp;</td>")
                                                Response_WriteLine("<td colspan=""2""><b>" & Me.GetLocationName(form_LocationIndex) & "</b>")
                                                Response_WriteLine("<form name=""frmLinkEditLocationFromEM"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromEM.submit()""><small>Edit</small></a>")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                                Response_WriteLine("</form>")
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right""><b>Team</b>&nbsp;</td>")
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine("<td><b>" & Me.ColorizeTeamName(Me.GetTeamName(sqlDataReader.Item("Me_TeamIndex"))) & "</b>")
                                                Else
                                                    Response_WriteLine("<td><b>" & Me.ColorizeFont(Me.GetTeamName(sqlDataReader.Item("Me_TeamIndex"))) & "</b>")
                                                End If
                                                Response_WriteLine("<form name=""frmLinkEditTeamFromEM"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditTeamFromEM.submit()""><small>Edit</small></a>")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & sqlDataReader.Item("Me_TeamIndex") & """>")
                                                Response_WriteLine("</form>")
                                                Response_WriteLine("</td>")
                                                Response_WriteLine("<td>Cannot associate to different Team.<br>Must instead create the Member under a new Team.</td></tr>")
                                                ' check for Nothing list, highlight this member's name in the list.  It *must* exist there.
                                                tempNames = Me.GetTeamMemberNames(sqlDataReader.Item("Me_TeamIndex"), True, True)
                                                If tempNames = "" Then
                                                    tempNames = "<font color=""red"">No Members Exist Yet</font>"
                                                Else
                                                    tempNames = Replace(tempNames, "; ", "<br>" & vbCrLf)
                                                    ' tempNames built from sqlDataReader.Item("Me_Name") so reference sqlDataReader.Item("Me_Name")
                                                    ' *not the possibly adjusted ADFULL*
                                                    ' tempNames has the title within it, so match strictly the NewName
                                                    If Not IsDBNull(sqlDataReader.Item("Me_Name")) Then
                                                        tempNames = Replace(tempNames, sqlDataReader.Item("Me_Name"), "<b>" & sqlDataReader.Item("Me_Name") & "</b>")
                                                    End If
                                                End If
                                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Team&nbsp;Members&nbsp;</td>")
                                                Response_WriteLine("<td colspan=""2"">" & tempNames & "")
                                                Response_WriteLine("<br>")
                                                Response_WriteLine("<form name=""frmLinkAddMemberFromEM"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                                Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkAddMemberFromEM.submit()""><small>Add Member</small></a>")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & sqlDataReader.Item("Me_TeamIndex") & """>")
                                                Response_WriteLine("</form>")
                                                Response_WriteLine("</td></tr>")
                                                ' highlight this member's email in the TeamEmail, if it exists in there...
                                                tempEmail = Me.GetTeamMemberNewEmails(sqlDataReader.Item("Me_TeamIndex"))
                                                ' tempEmail built from sqlDataReader.Item("Me_Email") so reference sqlDataReader.Item("Me_Email")
                                                ' *not the possibly adjusted ADE*
                                                If tempEmail = "" Then
                                                    tempEmail = "<font color=""red"">No Email Recipients for New Messages</font>"
                                                Else
                                                    tempEmail = LCase(tempEmail)
                                                    tempEmail = Replace(tempEmail, LCase(sqlDataReader.Item("Me_Email")), "<b>" & LCase(sqlDataReader.Item("Me_Email")) & "</b>")
                                                End If
                                                Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">New&nbsp;Message&nbsp;Emails&nbsp;</td><td colspan=""2"">" & tempEmail & "</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                                Response_WriteLine("<form name=""form_Method_EditMember"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                                Response_WriteLine("<input type=""hidden"" name=""form_MemberIndex"" value=""" & form_MemberIndex & """>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SortOrder&nbsp;</td>")
                                                sSqlString = "SELECT tab_Members.Me_Index, tab_Members.Me_SortOrder, tab_Members.Me_Name, tab_Members.Me_Active FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & sqlDataReader.Item("Me_TeamIndex") & " ORDER BY tab_Members.Me_SortOrder ASC;"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If Not sqlDataReader2.HasRows Then
                                                        ' should never get here as it exists already
                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">10<input type=""hidden"" name=""form_SortOrder"" value=""10""></td>")
                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">First Member member will be SortOrder=10.<br>")
                                                        Response_WriteLine("This is the order that the Member will appear in the list of Members.</td>")
                                                    Else
                                                        Response_WriteLine("<td><select name=""form_SortOrder"" class=""form-control"">")
                                                        maxSortOrder = 10
                                                        While sqlDataReader2.Read = True
                                                            If sqlDataReader2.Item("Me_SortOrder") > maxSortOrder Then
                                                                maxSortOrder = sqlDataReader2.Item("Me_SortOrder")
                                                            End If
                                                            If CStr(sqlDataReader2.Item("Me_Index")) = form_MemberIndex Then
                                                                Response_WriteLine("<option selected value=""AAA" & sqlDataReader2.Item("Me_SortOrder") & """>" & sqlDataReader2.Item("Me_SortOrder") & "</option>")
                                                            Else
                                                                Response_WriteLine("<option value=""AAA" & sqlDataReader2.Item("Me_SortOrder") & """>" & sqlDataReader2.Item("Me_SortOrder") & " - ")
                                                                If sqlDataReader2.Item("Me_Active") = "No" Then
                                                                    Response_WriteLine("* ")
                                                                End If
                                                                Response_WriteLine("" & sqlDataReader2.Item("Me_Name") & "</option>")
                                                            End If
                                                        End While
                                                        If sqlDataReader.Item("Me_SortOrder") < maxSortOrder Then
                                                            Response_WriteLine("<option value=""ZZZ"">Move to End</option>")
                                                        Else
                                                            ' no need to give a "ZZZ move to end" option, it's already at the end
                                                        End If
                                                        Response_WriteLine("</select></td>")
                                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Insert Before Selected.<br>")
                                                        Response_WriteLine("This is the order that the Member will appear in the list of Members.<br>")
                                                        Response_WriteLine("Organize the Team Members in this style:<br>")
                                                        Response_WriteLine("MD first, NP, PA, RN, LPN, MSA</td>")
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                                Response_WriteLine("</tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Title&nbsp;</td>")
                                                Response_WriteLine("<td><select name=""form_Title"" class=""form-control""><option></option>")
                                                sSqlString = "SELECT tab_Titles.Ti_Title, tab_Titles.Ti_Description FROM tab_Titles ORDER BY Ti_SortOrder;"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If Not sqlDataReader2.HasRows Then
                                                        ' none found
                                                    Else
                                                        ' Guess at title if:
                                                        ' title originally Nothing (at one time it was an optional field) or UserName changed
                                                        ' - username changing implies a different user took this slot
                                                        If IsDBNull(sqlDataReader.Item("Me_Title")) Or ADU <> UCase(sqlDataReader.Item("Me_Username")) Then
                                                            While sqlDataReader2.Read = True
                                                                If ADT <> "" Then
                                                                    Response_WriteLine("" & Me.CreateTitleOption(ADT, sqlDataReader2.Item("Ti_Title"), sqlDataReader2.Item("Ti_Description")) & "")
                                                                Else
                                                                    Response_WriteLine("<option value=""" & Replace(sqlDataReader2.Item("Ti_Title"), """", "&#34;") & """>" & sqlDataReader2.Item("Ti_Title") & "")
                                                                    If Not IsDBNull(sqlDataReader2.Item("Ti_Description")) Then
                                                                        Response_WriteLine("- " & sqlDataReader2.Item("Ti_Description") & "")
                                                                    End If
                                                                    Response_WriteLine("</option>")
                                                                End If
                                                            End While
                                                        Else
                                                            ' title already exists and didn't change name, keep title as is
                                                            ' reference original title instead of AD title when it comes to selecting it.
                                                            While sqlDataReader2.Read = True
                                                                Response_WriteLine("<option ")
                                                                If sqlDataReader.Item("Me_Title") = sqlDataReader2.Item("Ti_Title") Then
                                                                    Response_WriteLine("selected ")
                                                                End If
                                                                Response_WriteLine("value=""" & Replace(sqlDataReader2.Item("Ti_Title"), """", "&#34;") & """>" & sqlDataReader2.Item("Ti_Title") & "")
                                                                If Not IsDBNull(sqlDataReader2.Item("Ti_Description")) Then
                                                                    Response_WriteLine("- " & sqlDataReader2.Item("Ti_Description") & "")
                                                                End If
                                                                Response_WriteLine("</option>")
                                                            End While
                                                        End If
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Choose Title from the list.")
                                                If ADT <> "" Then
                                                    Response_WriteLine("&nbsp;(" & ADT & ")")
                                                End If
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top"" bgcolor=""#d6dbe9""><td align=""right"">Name&nbsp;</td>")
                                                Response_WriteLine("<td><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(ADFULL, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                                Response_WriteLine("<td>1. Enter full or partial name in form of ""Last, First"" or ""First Last""<br>")
                                                Response_WriteLine("2. Click <input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Look Up""> to search in Active Directory.<br>")
                                                Response_WriteLine("3. Username and Email address will be retrieved.<br>")
                                                Response_WriteLine("(If you are unable to pull up a name, enter ""VA\"" before the last name, first name to search all va.gov Domain)")
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Username&nbsp;</td>")
                                                Response_WriteLine("<td>" & ADU & "")
                                                Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & Replace(ADU, """", "&#34;") & """></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding Username.")
                                                ' BONUS - check this member's tab_Messages.Msg_Assigned field to see if that now needs adjusting
                                                sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(form_Username, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & sqlDataReader.Item("Me_TeamIndex") & ";"

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If sqlDataReader2.Read = True Then
                                                        thecount = sqlDataReader2.Item("THECOUNT")

                                                        If thecount > 0 Then
                                                            ' Found one
                                                            Response_WriteLine("<br>")
                                                            Response_WriteLine("<font color=""navy"">Note: Username has " & thecount & " Message(s) assigned to it.<br>")
                                                            Response_WriteLine("changing it will automatically update Assigned Open and Closed Messages to match.</font>")
                                                        End If
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                                ' BONUS - check other teams to see which will change, comes after submitting
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">SID&nbsp;</td>")
                                                Response_WriteLine("<td><small><i>" & "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & "</i></small>")
                                                Response_WriteLine("<input type=""hidden"" name=""form_SID"" value=""" & ADSID & """></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding SID.</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Email&nbsp;</td>")
                                                Response_WriteLine("<td><input type=""text"" name=""form_Email"" class=""form-control"" size=""40"" value=""" & Replace(ADE, """", "&#34;") & """ maxlength=""255""></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">example: first.last@va.gov</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">EmailNew&nbsp;</td>")
                                                Response_WriteLine("<td><select name=""form_EmailNew"" class=""form-control"">")
                                                Response_WriteLine("<option ")
                                                If form_EmailNew = "Yes" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""Yes"">Yes</option>")
                                                Response_WriteLine("<option ")
                                                If form_EmailNew = "No" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""No"">No</option>")
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">If Yes, member receives email for new and transferred messages.</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">EmailAssign&nbsp;</td>")
                                                Response_WriteLine("<td><select name=""form_EmailAssign"" class=""form-control"">")
                                                Response_WriteLine("<option ")
                                                If form_EmailAssign = "Yes" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""Yes"">Yes</option>")
                                                Response_WriteLine("<option ")
                                                If form_EmailAssign = "No" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""No"">No</option>")
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">If Yes, member receives email when the message is assigned to this member.</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">EmailStatus&nbsp;</td>")
                                                Response_WriteLine("<td><select name=""form_EmailStatus"" class=""form-control"">")
                                                Response_WriteLine("<option ")
                                                Response_WriteLine("selected ")
                                                Response_WriteLine("value=""No"">No</option>")
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Add/Edit Member - Functionality disabled for current implementation.<br>")
                                                Response_WriteLine("* Note - Members previously setup 'Yes' will continue email status until manual adjustment.</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">ShowOn&nbsp;</td>")
                                                Response_WriteLine("<td><select name=""form_ShowOn"" class=""form-control"">")
                                                Response_WriteLine("<option ")
                                                If form_ShowOn = "Yes" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""Yes"">Yes</option>")
                                                Response_WriteLine("<option ")
                                                If form_ShowOn = "No" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""No"">No</option>")
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Is Member name shown appended to the Team name on the Team Selection section of a New Message?<br>")
                                                Response_WriteLine("Yes = Displays the Member name<br>")
                                                Response_WriteLine("No = Does not display the Member name")
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Active&nbsp;</td>")
                                                Response_WriteLine("<td><select name=""form_Active"" class=""form-control"">")
                                                Response_WriteLine("<option ")
                                                If form_Active = "Yes" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""Yes"">Yes</option>")
                                                Response_WriteLine("<option ")
                                                If form_Active = "No" Then
                                                    Response_WriteLine("selected ")
                                                End If
                                                Response_WriteLine("value=""No"">No</option>")
                                                Response_WriteLine("</select></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Yes = Member can be assigned Messages.<br>")
                                                Response_WriteLine("No = Member still part of team but cannot be assigned Messages.")
                                                Response_WriteLine("</td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                                Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td>")
                                                Response_WriteLine("<td><input type=""text"" name=""form_Notes"" class=""form-control"" value=""" & Replace(form_Notes, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                                Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain Member settings")
                                                Response_WriteLine("</td></tr>							")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                                Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Save Changes to Member""></center></td></tr>")
                                                Response_WriteLine("</form>")
                                                Response_WriteLine("</table>")
                                                Response_WriteLine("</td></tr></table>")
                                                Response_WriteLine("</p>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        ' 000 admins will default to this member's site
                                        Me.ShowMembersTable(0, form_Username)
                                        Me.ShowTeamsTable(form_LocationIndex)

                                End Select  ' form_Submit = "Look Up", "Change Checked Fields Too"

                            Case "EditAdmin"
                                Dim form_OriginalAdminUsername
                                ' Original Admin Username is needed as it's the "Unique Field" in access and it has the chance of being renamed.
                                form_OriginalAdminUsername = Request.Form("form_OriginalAdminUsername")

                                If form_Submit = "Choose Selected Account" Then
                                    ' reset the unique field back to the original
                                    form_Username = form_OriginalAdminUsername
                                    If ADloop = "x" Then
                                        Response_WriteLine("<p><font color=""red"">Selection cancelled.</font></p>")
                                    Else
                                        If ADloop = "" Then
                                            Response_WriteLine("<p><font color=""red"">Selection submitted but nothing was chosen.</font></p>")
                                        Else
                                            ' name chosen
                                            Response_WriteLine("<p><font color=""green"">Selection complete, auto-filling fields: Name, Username, SID, Email</font></p>")
                                        End If
                                    End If
                                End If

                                If form_Submit = "Look Up" Then
                                    ' name entered, "Look Up" submitted, load username and email from AD
                                    strADResults = Me.ADNameSearch(form_Name)
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("strADResults=" & strADResults & "<br>")
                                    End If
                                    If strADResults <> "" Then
                                        ' One or more hits found, show the form to pick the right one
                                        ' strFirstname & "_^_" & strLastname & "_^_" & strEmail & "_^_" & strTitle & "_^_" & strFullname & "_^_" & sDomain\strUsername & "_^_" & strSID & "_^__ROW_"
                                        Response_WriteLine("<form name=""frmMethodEditAdminAD"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Name"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_OriginalAdminUsername"" value=""" & form_OriginalAdminUsername & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditAdmin"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""ChoseAD"">")
                                        Response_WriteLine("<table>")
                                        Response_WriteLine("<tr><th colspan=""5"" bgcolor=""#d6dbe9"">Choose the closest match or cancel</th></tr>")
                                        strADResults = strADResults & "zzz"

                                        ADrows = Split(strADResults, "_ROW_")
                                        ADloop = 0
                                        Do While ADrows(ADloop) <> "zzz"

                                            ADarray = Split(ADrows(ADloop), "_^_")
                                            If ADarray(0) <> "" Then
                                                ADF = ADarray(0)
                                                If ADarray(1) <> "zzz" Then
                                                    ADL = ADarray(1)
                                                    If ADarray(2) <> "zzz" Then
                                                        ADE = ADarray(2)
                                                        If ADarray(3) <> "zzz" Then
                                                            ADT = ADarray(3)
                                                            If ADarray(4) <> "zzz" Then
                                                                ADFULL = ADarray(4)
                                                                If ADarray(5) <> "zzz" Then
                                                                    ADU = ADarray(5)
                                                                    If ADarray(6) <> "zzz" Then
                                                                        ADSID = ADarray(6)
                                                                    End If
                                                                End If
                                                            End If
                                                        End If
                                                    End If
                                                End If
                                            End If
                                            ' all fields could in theory have a " in them except for the SID
                                            Response_WriteLine("<input type=""hidden"" name=""ADF" & ADloop & """ value=""" & Replace(ADF, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADL" & ADloop & """ value=""" & Replace(ADL, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADE" & ADloop & """ value=""" & Replace(ADE, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADT" & ADloop & """ value=""" & Replace(ADT, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADFULL" & ADloop & """ value=""" & Replace(ADFULL, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADU" & ADloop & """ value=""" & Replace(ADU, """", "&#34;") & """>")
                                            Response_WriteLine("<input type=""hidden"" name=""ADSID" & ADloop & """ value=""" & ADSID & """>")
                                            If ADloop Mod 2 = 0 Then
                                                Response_WriteLine("<tr bgcolor=""#eeeeee""><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                            Else
                                                Response_WriteLine("<tr><td><input type=""radio"" name=""form_AD"" value=""" & ADloop & """></td>")
                                                Response_WriteLine("<td>" & ADFULL & "</td><td>" & ADU & "</td><td>" & ADE & "</td><td>" & ADT & "</td></tr>")
                                            End If
                                            ADloop = ADloop + 1
                                        Loop
                                        ' these values were the last of the loop so re-initialize
                                        ADloop = ""
                                        ADF = ""
                                        ADL = ""
                                        ADE = ""
                                        ADT = ""
                                        ADFULL = ""
                                        ADU = ""
                                        ADSID = ""
                                        Response_WriteLine("<tr><td>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADFULLx"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADEx"" value=""" & Replace(form_Email, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADUx"" value=""" & Replace(form_Username, """", "&#34;") & """>")
                                        Response_WriteLine("<input type=""hidden"" name=""ADSIDx"" value=""" & form_SID & """>")
                                        Response_WriteLine("<input type=""radio"" name=""form_AD"" value=""x""></td>")
                                        Response_WriteLine("<td colspan=""4"">Cancel</td>")
                                        Response_WriteLine("</tr>")
                                        Response_WriteLine("<tr><td colspan=""5""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Choose Selected Account""></center></td></tr>")
                                        Response_WriteLine("</table>")
                                        Response_WriteLine("</form>")
                                    End If

                                Else

                                    If form_Method = "StoreMe" Then
                                        ' new EditAdmin fields submitted, store them

                                        form_Error = ""
                                        If form_Username = "" Then
                                            form_Error = form_Error & " Username"
                                        Else
                                            If InStr(form_Username, "\") Then
                                                ' good, has "\" in the value
                                            Else
                                                ' Missing Valid-Domain\Username
                                                form_Error = form_Error & " Valid-Domain\Username"
                                            End If
                                        End If
                                        If form_SID = "" Then
                                            form_Error = form_Error & " SID"
                                        End If
                                        If form_SiteNum = "" Then
                                            form_Error = form_Error & " SiteNum"
                                        End If
                                        If form_Access = "" Then
                                            form_Error = form_Error & " Access"
                                        End If
                                        If form_Type = "" Then
                                            form_Error = form_Error & " Type"
                                        Else
                                            If form_Type = "None Found" Then
                                                form_Error = form_Error & " Type(create-Types-first)"
                                            End If
                                        End If
                                        If form_Name = "" Then
                                            form_Error = form_Error & " Name"
                                        End If
                                        If form_Email = "" Then
                                            form_Error = form_Error & " Email"
                                        Else
                                            ' not Nothing, ensure valid
                                            If Not Me.isValidEmail(form_Email) Then
                                                ' Missing Valid-Email
                                                form_Error = form_Error & " Valid-Email"
                                            End If
                                        End If
                                        ' form_FlagOn guaranteed to be "Yes" or "No"
                                        If form_Notes = "" Then
                                            form_Error = form_Error & " Notes"
                                        End If
                                        If form_SiteNum = "000" And form_Sites = "" Then
                                            form_Error = form_Error & " Must Select at least one Site below for SiteNum 000"
                                        End If

                                        If form_Error = "" Then
                                            ' safe to update

                                            sSqlString = "SELECT * FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_OriginalAdminUsername, "'", "''") & "';"

                                            MyCommand.CommandText = sSqlString

                                            Try
                                                If MyConnection.State = ConnectionState.Closed Then
                                                    MyConnection.Open()
                                                End If

                                                sqlDataReader = MyCommand.ExecuteReader

                                                If Not sqlDataReader.Read Then
                                                    Response_WriteLine("<p><font color=""red"">Error - " & form_OriginalAdminUsername & " not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                                Else
                                                    ' Unique field - do this first
                                                    ' switch to uppercase
                                                    form_Username = UCase(form_Username)
                                                    If sqlDataReader.Item("Adm_Username") <> form_Username Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Username = '" & Replace(form_Username, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_OriginalAdminUsername, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">Username updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating Username.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    ' SID used to be a NULL field so many are still NULL
                                                    If sqlDataReader.Item("Adm_SID") <> form_SID Or (IsDBNull(sqlDataReader.Item("Adm_SID")) And form_SID <> "") Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_SID = '" & form_SID & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">SID updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating SID.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    ' Name used to be an optional field so many are still NULL
                                                    If sqlDataReader.Item("Adm_Name") <> form_Name Or (IsDBNull(sqlDataReader.Item("Adm_Name")) And form_Name <> "") Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">Name updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating Name.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    ' first convert to Lowercase
                                                    form_Email = LCase(form_Email)
                                                    ' Email used to be an optional field so many are still NULL
                                                    If sqlDataReader.Item("Adm_Email") <> form_Email Or (IsDBNull(sqlDataReader.Item("Adm_Email")) And form_Email <> "") Then
                                                        If form_Email = "" Then
                                                            ' form field blank so remove Email from database
                                                            UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Email = NULL WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        Else
                                                            ' form field valid so store updated Email
                                                            UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Email = '" & Replace(form_Email, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        End If
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">Email updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating Email.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    ' do these 3 with new form_Username as they rely on unique field Username	
                                                    If sqlDataReader.Item("Adm_SiteNum") <> form_SiteNum Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_SiteNum = '" & Replace(form_SiteNum, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">SiteNum updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating SiteNum.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    If sqlDataReader.Item("Adm_AccessLevel") <> form_Access Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_AccessLevel = '" & Replace(form_Access, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">AccessLevel updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating AccessLevel.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    If sqlDataReader.Item("Adm_Type") <> form_Type Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Type = '" & Replace(form_Type, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">Type updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating Type.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    If sqlDataReader.Item("Adm_FlagOn") <> form_FlagOn Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_FlagOn = '" & form_FlagOn & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">FlagOn updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating FlagOn.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    If IsDBNull(sqlDataReader.Item("Adm_Notes")) Then
                                                        memoNotes = ""
                                                    Else
                                                        memoNotes = sqlDataReader.Item("Adm_Notes")
                                                    End If
                                                    If memoNotes <> form_Notes Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Notes = '" & Replace(form_Notes, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">Notes updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating Notes.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If

                                                    If sqlDataReader.Item("Adm_Sites") <> form_Sites Then
                                                        UpdateTableRecord("UPDATE tab_Admins SET tab_Admins.Adm_Sites = '" & Replace(form_Sites, "'", "''") & "' WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';")
                                                        'On Error Resume Next
                                                        If Err.Number = 0 Then
                                                            Response_WriteLine("<p><font color=""green"">Selected Sites updated successfully.</font></p>")
                                                        Else
                                                            Response_WriteLine("<p><font color=""red"">ERROR updating Selected Sites.</font></p>")
                                                            Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                        End If
                                                        'On Error GoTo 0

                                                        ' StoreAuditAdmin(AA_Action, AA_Details)
                                                        errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                        If errstore <> "Success" Then
                                                            Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                        End If
                                                    Else
                                                        ' skip, not changed
                                                    End If
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                            ' note that if someone changes SELF
                                            ' they would maintain their previous access rights while viewing this
                                            ' so check for new status
                                            ' menu bar will still have old values, but this form will now be customized to the AdminSite value
                                            If UCase(Me.UserName) = form_Username Then
                                                Response.Write("<p>Editing Self!  What are you doing?</p>")
                                                ' load new AdminAccess variables
                                                Me.CheckAdmin()
                                            End If

                                        Else
                                            ' missing info, try again
                                            Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            ' update query field back to the original since it wasn't changed
                                            form_Username = form_OriginalAdminUsername
                                        End If

                                    End If  ' form_Method = "StoreMe"

                                    sSqlString = "SELECT * FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If Not sqlDataReader.Read Then
                                            Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Admin, """ & form_Username & """ not found in database.</font></p>")
                                        Else
                                            If IsDBNull(sqlDataReader.Item("Adm_Notes")) Then
                                                memoNotes = "Edit by " & Me.UserName & " on " & theDate
                                            Else
                                                memoNotes = sqlDataReader.Item("Adm_Notes")
                                            End If

                                            ' either first time in, or name chosen/cancelled from AD
                                            If form_Method = "ChoseAD" Then
                                                ' title not used for Admins
                                                ' ADFULL not used, regenerate without middle initial and in "First Last" form
                                                If ADloop = "x" Or ADloop = "" Then
                                                    ' x means cancel clicked, use the previously typed in value still
                                                    ADFULL = Request.Form("ADFULLx")
                                                    ADE = Request.Form("ADEx")
                                                    ADU = Request.Form("ADUx")
                                                    ADSID = Request.Form("ADSIDx")
                                                Else
                                                    ' AD form used, name selected, load First, Last, Email, Username and SID
                                                    ADF = Request.Form("ADF" & ADloop)
                                                    ADL = Request.Form("ADL" & ADloop)
                                                    ADE = Request.Form("ADE" & ADloop)
                                                    ' Title not used
                                                    ' ADT = Request.Form("ADT" & ADloop)
                                                    ADU = Request.Form("ADU" & ADloop)
                                                    ADSID = Request.Form("ADSID" & ADloop)

                                                    ' ADFULL not used from display name.  generate instead
                                                    ' use "first last" notation
                                                    ' ADFULL = Request.Form("ADFULL" & ADloop)
                                                    ADFULL = ADF & " " & ADL
                                                    If ADFULL = " " Then
                                                        ADFULL = ""
                                                    End If
                                                End If
                                            Else
                                                ' first time into AD search, use the existing database values still
                                                ADFULL = sqlDataReader.Item("Adm_Name")
                                                ADU = sqlDataReader.Item("Adm_Username")
                                                ADE = sqlDataReader.Item("Adm_Email")
                                                ADSID = sqlDataReader.Item("Adm_SID")
                                                If IsDBNull(ADFULL) Then ADFULL = ""
                                                If IsDBNull(ADU) Then ADU = ""
                                                If IsDBNull(ADE) Then ADE = ""
                                                If IsDBNull(ADSID) Then ADSID = ""
                                            End If
                                            ADU = UCase(ADU)
                                            ADE = LCase(ADE)
                                            Response_WriteLine("<p>")
                                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                            Response_WriteLine("<Table cellspacing=""0"">")
                                            Response_WriteLine("<form name=""form_Method_EditAdmin"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditAdmin"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_OriginalAdminUsername"" value=""" & form_Username & """>")
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit an Admin</th></tr>")
                                            'Response_WriteLine("<tr><td bgcolor=""#dbe4f0"" colspan=""3""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr valign=""top"" bgcolor=""#d6dbe9""><td align=""right"">Name&nbsp;</td>")
                                            Response_WriteLine("<td><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(ADFULL, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                            Response_WriteLine("<td>1. Enter full or partial name in form of ""Last, First"" or ""First Last""<br>")
                                            Response_WriteLine("2. Click <input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Look Up""> to search in Active Directory.<br>")
                                            Response_WriteLine("3. Username and Email address will be retrieved.<br>")
                                            Response_WriteLine("(If you are unable to pull up a name, enter ""VA\"" before the last name, first name to search all va.gov Domain)")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Username&nbsp;</td>")
                                            Response_WriteLine("<td>" & ADU & "")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & Replace(ADU, """", "&#34;") & """></td>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Sites"" id=""ID_Sites"" value=""""></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding Username.</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">SID&nbsp;</td><td>")
                                            Response_WriteLine("<small><i>" & "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & "</i></small>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_SID"" value=""" & ADSID & """></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">Lookup Name in AD to obtain the corresponding SID.</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#d6dbe9"">&nbsp;</td><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#d6dbe9"" align=""right"">Email&nbsp;</td>")
                                            Response_WriteLine("<td><input type=""text"" name=""form_Email"" class=""form-control"" value=""" & Replace(ADE, """", "&#34;") & """ size=""40"" maxlength=""255""></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">example: first.last@va.gov</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum&nbsp;</td><td>")
                                            Response_WriteLine("<select name=""form_SiteNum"" id=""ID_Select"" class=""form-control"">")
                                            Response_WriteLine("<option></option>")
                                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                            If Me.AdminSite = "000" Then
                                                ' don't limit by S, meaning show all sites assigned
                                                sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum IN(" & Me.AdminSites & ",'000')"
                                            Else
                                                ' limit by chosen S
                                                sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                            End If
                                            sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("sSqlString=" & sSqlString & "<br>")
                                            End If

                                            MyCommand2.CommandText = sSqlString

                                            Try
                                                If MyConnection2.State = ConnectionState.Closed Then
                                                    MyConnection2.Open()
                                                End If

                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                If Not sqlDataReader2.HasRows Then
                                                    ' none found
                                                Else
                                                    While sqlDataReader2.Read = True
                                                        Response_WriteLine("<option ")
                                                        If sqlDataReader.Item("Adm_SiteNum") = sqlDataReader2.Item("Si_SiteNum") Then
                                                            Response_WriteLine("selected ")
                                                        End If
                                                        Response_WriteLine("value=""" & sqlDataReader2.Item("Si_SiteNum") & """>" & sqlDataReader2.Item("Si_SiteNum") & " - ")
                                                        If sqlDataReader2.Item("Si_Active") = "No" Then
                                                            Response_WriteLine("* ")
                                                        End If
                                                        Response_WriteLine("" & Replace(sqlDataReader2.Item("Si_Name"), "Choose Site", "") & "</option>")
                                                    End While
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                            Response_WriteLine("</select>")
                                            Response_WriteLine("</td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">000 = Selected Sites (checked below)<br>")
                                            Response_WriteLine("Or pick a Site Number to limit access to that site</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Access&nbsp;</td>")
                                            Response_WriteLine("<td><select name=""form_Access"" class=""form-control"">")
                                            Response_WriteLine("<option ")
                                            If sqlDataReader.Item("Adm_AccessLevel") = "Admin" Then
                                                Response_WriteLine("selected ")
                                            End If
                                            Response_WriteLine("value=""Admin"">Admin</option>")
                                            Response_WriteLine("<option ")
                                            If sqlDataReader.Item("Adm_AccessLevel") = "Site" Then
                                                Response_WriteLine("selected ")
                                            End If
                                            Response_WriteLine("value=""Site"">Site</option>")
                                            Response_WriteLine("</select></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">Admin = Can View and Edit all Messages. Can Edit Setup<br>")
                                            Response_WriteLine("Site = Can View and Edit all Messages.  Cannot View or Edit Setup.")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type&nbsp;</td>")
                                            Response_WriteLine("<td><select name=""form_Type"" class=""form-control"">")
                                            optionCount = 0
                                            optionItem = ""
                                            sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons"
                                            If Me.AdminType = "All" Then
                                                ' don't limit by Type, meaning show all types
                                            Else
                                                ' limit by Type
                                                sSqlString = sSqlString & " WHERE tab_Reasons.Re_Type = '" & Me.AdminType & "'"
                                            End If
                                            sSqlString = sSqlString & " ORDER BY tab_Reasons.Re_Type;"

                                            MyCommand2.CommandText = sSqlString

                                            Try
                                                If MyConnection2.State = ConnectionState.Closed Then
                                                    MyConnection2.Open()
                                                End If

                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                If Not sqlDataReader2.HasRows Then
                                                    optionCount = 0
                                                    optionItem = "<option value=""None Found"">None Found</option>" & vbCrLf
                                                Else
                                                    While sqlDataReader2.Read = True
                                                        ' Exclude FEE and PACT as per John P. TJD
                                                        If sqlDataReader2.Item("REASONTYPE") <> "FEE" And sqlDataReader2.Item("REASONTYPE") <> "PACT" Then
                                                            optionItem = optionItem & "<option value=""" & sqlDataReader2.Item("REASONTYPE") & """"
                                                            If sqlDataReader.Item("Adm_Type") = sqlDataReader2.Item("REASONTYPE") Then
                                                                optionItem = optionItem & " selected"
                                                            End If
                                                            optionItem = optionItem & ">" & sqlDataReader2.Item("REASONTYPE") & "</option>" & vbCrLf
                                                            optionCount = optionCount + 1
                                                        End If
                                                    End While
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                            ' insert "All" at the top
                                            If sqlDataReader.Item("Adm_Type") = "All" Then
                                                optionItem = "<option value=""All"" selected>All</option>" & vbCrLf & optionItem
                                            Else
                                                optionItem = "<option value=""All"">All</option>" & vbCrLf & optionItem
                                            End If
                                            optionCount = optionCount + 1

                                            Response.Write(optionItem)
                                            Response_WriteLine("</select></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">Choose the Type of Teams that this admin will manage</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">FlagOn&nbsp;</td>")
                                            Response_WriteLine("<td><select name=""form_FlagOn"" class=""form-control"">")
                                            Response_WriteLine("<option ")
                                            If sqlDataReader.Item("Adm_FlagOn") = "Yes" Then
                                                Response_WriteLine("selected ")
                                            End If
                                            Response_WriteLine("value=""Yes"">Yes</option>")
                                            Response_WriteLine("<option ")
                                            If sqlDataReader.Item("Adm_FlagOn") = "No" Then
                                                Response_WriteLine("selected ")
                                            End If
                                            Response_WriteLine("value=""No"">No</option>")
                                            Response_WriteLine("</select></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">Used for ""Message Escalation"" recipient when these are all true:<br>")
                                            Response_WriteLine("- FlagOn  to ""Yes""<br>")
                                            Response_WriteLine("- all Locations under this SiteNum<br>")
                                            Response_WriteLine("- when the Admin's SiteNum is ""000"" or matches the Site<br>")
                                            Response_WriteLine("- when the Admin's Type is ""All"" or matches the Location's Type")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td>")
                                            Response_WriteLine("<td><input type=""text"" name=""form_Notes"" class=""form-control"" size=""40"" value=""" & Replace(memoNotes, """", "&#34;") & """ maxlength=""255""></td>")
                                            Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain Admin privileges</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Save Changes to Admin""></center></td></tr>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</Table>")
                                            Response_WriteLine("</td></tr></table>")
                                            Response_WriteLine("</p>")

                                            sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                            If Me.AdminSite = "000" Then
                                                sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum <> '000'"
                                            Else
                                                ' limit by chosen S
                                                sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                            End If
                                            sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("sSqlString=" & sSqlString & "<br>")
                                            End If

                                            MyCommand2.CommandText = sSqlString
                                            Response_WriteLine("<p><div class=""000 box"" style=""width:50%;border:1px solid #58589d;background-color: #fff;""><strong style=""color: #ff0000;"">Selected Sites for SiteNum 000:</strong>")
                                            Try
                                                If MyConnection2.State = ConnectionState.Closed Then
                                                    MyConnection2.Open()
                                                End If

                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                If Not sqlDataReader2.HasRows Then
                                                    ' none found
                                                Else
                                                    Response_WriteLine("<fieldset>")
                                                    While sqlDataReader2.Read = True
                                                        If sqlDataReader.Item("Adm_Sites").ToString.Contains("'" & sqlDataReader2.Item("Si_SiteNum") & "'") Then
                                                            Response_WriteLine("<input type=""checkbox"" checked id=""" & "'" & sqlDataReader2.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader2.Item("Si_SiteNum") & " - ")
                                                        Else
                                                            Response_WriteLine("<input type=""checkbox"" id=""" & "'" & sqlDataReader2.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader2.Item("Si_SiteNum") & " - ")
                                                        End If
                                                        If sqlDataReader2.Item("Si_Active") = "No" Then
                                                            Response_WriteLine("* ")
                                                        End If
                                                        Response_WriteLine("" & Replace(sqlDataReader2.Item("Si_Name"), "Choose Site", "") & "</input><br/>")
                                                    End While
                                                    Response_WriteLine("</fieldset>")
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try
                                            Response_WriteLine("</div></p>")
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    Me.ShowAdminsTable(form_Username)

                                End If ' form_Submit = "Look Up"

                            Case "EditADGroup"

                                Dim form_OriginalADGroup
                                ' Original Admin Username is needed as it's the "Unique Field" in access and it has the chance of being renamed.
                                form_OriginalADGroup = Request.Form("form_OriginalADGroup")

                                If form_Method = "StoreMe" Then
                                    ' new EditADGroup fields submitted, store them

                                    form_Error = ""
                                    If form_SiteNum = "" Then
                                        form_Error = form_Error & " SiteNum"
                                    End If
                                    If form_Access = "" Then
                                        form_Error = form_Error & " Access Level"
                                    End If
                                    If form_Type = "" Then
                                        form_Error = form_Error & " Type"
                                    Else
                                        If form_Type = "None Found" Then
                                            form_Error = form_Error & " Type(create-Types-first)"
                                        End If
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " AD Group Name"
                                    End If
                                    If form_SiteNum = "000" And form_Sites = "" Then
                                        form_Error = form_Error & " Must Select at least one Site below for SiteNum 000"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to update

                                        sSqlString = "SELECT * FROM tab_ADGroups WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_OriginalADGroup, "'", "''") & "';"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">Error - <i>" & form_OriginalADGroup & "</i> not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            Else
                                                If sqlDataReader.Item("AD_GroupName") <> form_Name Then
                                                    UpdateTableRecord("UPDATE tab_ADGroups SET tab_ADGroups.AD_GroupName = '" & Replace(form_Name, "'", "''") & "'" & " WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_OriginalADGroup, "'", "''") & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">AD Group Name updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating AD Group Name.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit ADGroup", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                ' do these 3 with new form_Name as they rely on unique field AD_GroupName
                                                If sqlDataReader.Item("AD_SiteNum") <> form_SiteNum Then
                                                    UpdateTableRecord("UPDATE tab_ADGroups SET tab_ADGroups.AD_SiteNum = '" & Replace(form_SiteNum, "'", "''") & "'" & " WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">SiteNum updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating SiteNum.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit ADGroup", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("AD_AccessLevel") <> form_Access Then
                                                    UpdateTableRecord("UPDATE tab_ADGroups SET tab_ADGroups.AD_AccessLevel = '" & form_Access & "'" & " WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">AccessLevel updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating AccessLevel.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit ADGroup", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("AD_Type") <> form_Type Then
                                                    UpdateTableRecord("UPDATE tab_ADGroups SET tab_ADGroups.AD_Type = '" & Replace(form_Type, "'", "''") & "'" & " WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Type updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Type.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit ADGroup", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If sqlDataReader.Item("AD_Sites") <> form_Sites Then
                                                    UpdateTableRecord("UPDATE tab_ADGroups SET tab_ADGroups.AD_Sites = '" & Replace(form_Sites, "'", "''") & "'" & " WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Sites updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Sites.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit ADGroup", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                        ' update query field back to the original since it wasn't changed
                                        form_Name = form_OriginalADGroup
                                    End If

                                End If  ' form_Method = "StoreMe"

                                sSqlString = "SELECT * FROM tab_ADGroups WHERE tab_ADGroups.AD_GroupName LIKE '" & form_Name & "';"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        Response_WriteLine("<p><font color=""red"">ERROR - cannot edit AD Group, """ & form_Name & """ not found in database.</font></p>")
                                    Else
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<Table cellspacing=""0"">")
                                        Response_WriteLine("<form name=""form_Method_EditADGroup"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditADGroup"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Sites"" id=""ID_Sites"" value=""""></td>")
                                        Response_WriteLine("<input type=""hidden"" name=""form_OriginalADGroup"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit an AD Group</th></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum&nbsp;</td><td>")
                                        Response_WriteLine("<select name=""form_SiteNum"" id=""ID_Select"" class=""form-control"">")
                                        Response_WriteLine("<option></option>")
                                        sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                        If Me.AdminSite = "000" Then
                                            ' don't limit by S, meaning show all sites assigned
                                            sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum IN(" & Me.AdminSites & ",'000')"
                                        Else
                                            ' limit by chosen S
                                            sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                        End If
                                        sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand2.CommandText = sSqlString

                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                ' none found
                                            Else
                                                While sqlDataReader2.Read = True
                                                    Response_WriteLine("<option ")
                                                    If sqlDataReader.Item("AD_SiteNum") = sqlDataReader2.Item("Si_SiteNum") Then
                                                        Response_WriteLine("selected ")
                                                    End If
                                                    Response_WriteLine("value=""" & sqlDataReader2.Item("Si_SiteNum") & """>" & sqlDataReader2.Item("Si_SiteNum") & " - " & Replace(sqlDataReader2.Item("Si_Name"), "Choose Site", "") & "</option>")
                                                End While
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        Response_WriteLine("</select>")
                                        Response_WriteLine("</td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">000 = Selected Sites (checked below)<br>")
                                        Response_WriteLine("Or pick a Site Number to limit access to that site</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Access&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Access"" class=""form-control"">")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("AD_AccessLevel") = "Admin" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""Admin"">Admin</option>")
                                        Response_WriteLine("<option ")
                                        If sqlDataReader.Item("AD_AccessLevel") = "Site" Then
                                            Response_WriteLine("selected ")
                                        End If
                                        Response_WriteLine("value=""Site"">Site</option>")
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Admin = Can View and Edit all Messages. Can Edit Setup<br>")
                                        Response_WriteLine("Site = Can View and Edit all Messages.  Cannot View or Edit Setup.")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type&nbsp;</td>")
                                        Response_WriteLine("<td><select name=""form_Type"" class=""form-control"">")
                                        optionCount = 0
                                        optionItem = ""
                                        sSqlString = "SELECT DISTINCT(tab_Reasons.Re_Type) AS REASONTYPE FROM tab_Reasons"
                                        If Me.AdminType = "All" Then
                                            ' don't limit by Type, meaning show all types
                                        Else
                                            ' limit by Type
                                            sSqlString = sSqlString & " WHERE tab_Reasons.Re_Type = '" & Me.AdminType & "'"
                                        End If
                                        sSqlString = sSqlString & " ORDER BY tab_Reasons.Re_Type;"

                                        MyCommand2.CommandText = sSqlString

                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                optionCount = 0
                                                optionItem = "<option value=""None Found"">None Found</option>" & vbCrLf
                                            Else
                                                While sqlDataReader2.Read = True
                                                    ' Exclude FEE and PACT as per John P. TJD
                                                    If sqlDataReader2.Item("REASONTYPE") <> "FEE" And sqlDataReader2.Item("REASONTYPE") <> "PACT" Then
                                                        optionItem = optionItem & "<option value=""" & sqlDataReader2.Item("REASONTYPE") & """"
                                                        If sqlDataReader.Item("AD_Type") = sqlDataReader2.Item("REASONTYPE") Then
                                                            optionItem = optionItem & " selected"
                                                        End If
                                                        optionItem = optionItem & ">" & sqlDataReader2.Item("REASONTYPE") & "</option>" & vbCrLf
                                                        optionCount = optionCount + 1
                                                    End If
                                                End While
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                        ' insert "All" at the top
                                        If sqlDataReader.Item("AD_Type") = "All" Then
                                            optionItem = "<option value=""All"" selected>All</option>" & vbCrLf & optionItem
                                        Else
                                            optionItem = "<option value=""All"">All</option>" & vbCrLf & optionItem
                                        End If
                                        optionCount = optionCount + 1

                                        Response.Write(optionItem)
                                        Response_WriteLine("</select></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Choose the Type of Teams that this group will manage</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">AD Group Name&nbsp;</td><td><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(form_Name, """", "&#34;") & """ size=""40"" maxlength=""255"" readonly=""true""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Active Directory Distribution List name.<br>")
                                        Response_WriteLine("It allows an Owner to manage the membership.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Save Changes to AD Group""></center></td></tr>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</Table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p>")

                                        sSqlString = "SELECT tab_Sites.Si_SiteNum, tab_Sites.Si_Name, tab_Sites.Si_Active FROM tab_Sites"
                                        If Me.AdminSite = "000" Then
                                            sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum <> '000'"
                                        Else
                                            ' limit by chosen S
                                            sSqlString = sSqlString & " WHERE tab_Sites.Si_SiteNum = '" & Me.AdminSite & "'"
                                        End If
                                        sSqlString = sSqlString & " ORDER BY tab_Sites.Si_SiteOrder;"
                                        If _clsMessageVAR.BDebug = True Then
                                            Response.Write("sSqlString=" & sSqlString & "<br>")
                                        End If

                                        MyCommand2.CommandText = sSqlString
                                        Response_WriteLine("<p><div class=""000 box"" style=""width:50%;border:1px solid #58589d;background-color: #fff;""><strong style=""color: #ff0000;"">Selected Sites for SiteNum 000:</strong>")
                                        Try
                                            If MyConnection2.State = ConnectionState.Closed Then
                                                MyConnection2.Open()
                                            End If

                                            sqlDataReader2 = MyCommand2.ExecuteReader

                                            If Not sqlDataReader2.HasRows Then
                                                ' none found
                                            Else
                                                Response_WriteLine("<fieldset>")
                                                While sqlDataReader2.Read = True
                                                    If sqlDataReader.Item("AD_Sites").ToString.Contains("'" & sqlDataReader2.Item("Si_SiteNum") & "'") Then
                                                        Response_WriteLine("<input type=""checkbox"" checked id=""" & "'" & sqlDataReader2.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader2.Item("Si_SiteNum") & " - ")
                                                    Else
                                                        Response_WriteLine("<input type=""checkbox"" id=""" & "'" & sqlDataReader2.Item("Si_SiteNum") & "'" & """>&nbsp;" & sqlDataReader2.Item("Si_SiteNum") & " - ")
                                                    End If
                                                    If sqlDataReader2.Item("Si_Active") = "No" Then
                                                        Response_WriteLine("* ")
                                                    End If
                                                    Response_WriteLine("" & Replace(sqlDataReader2.Item("Si_Name"), "Choose Site", "") & "</input><br/>")
                                                End While
                                                Response_WriteLine("</fieldset>")
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                            If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try
                                        Response_WriteLine("</div></p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowADGroupsTable(Me.AdminSite)

                            Case "EditScript"
                                Dim ScIndex, ScReasonIndex, ScLocationIndex, ScDetails, ScNotes
                                If form_Method = "StoreMe" Then
                                    ' new EditScript fields submitted, store them

                                    form_Error = ""
                                    If form_ScriptIndex = "" Then
                                        form_Error = form_Error & " ScriptIndex"
                                    End If
                                    ' not editable: form_LocationIndex
                                    ' not editable: form_ReasonIndex
                                    If form_Details = "" Then
                                        form_Error = form_Error & " Script"
                                    End If
                                    If form_Notes = "" Then
                                        form_Error = form_Error & " Notes"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to update

                                        sSqlString = "SELECT * FROM tab_Scripts WHERE Tab_Scripts.Sc_Index = " & form_ScriptIndex & ";"

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">Error - Index " & form_ScriptIndex & " not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            Else
                                                ' multiple nVarChar(MAX) fields in sSqlString need the fields stored to variables sequentially
                                                ScIndex = sqlDataReader.Item("Sc_Index")
                                                ScReasonIndex = sqlDataReader.Item("Sc_ReasonIndex")
                                                ScLocationIndex = sqlDataReader.Item("Sc_LocationIndex")
                                                ScDetails = sqlDataReader.Item("Sc_Details")
                                                ScNotes = sqlDataReader.Item("Sc_Notes")

                                                If IsDBNull(ScDetails) Then
                                                    ScDetails = ""
                                                End If
                                                If ScDetails <> form_Details Then
                                                    UpdateTableRecord("UPDATE tab_Scripts SET tab_Scripts.Sc_Details = '" & Replace(form_Details, "'", "''") & "' WHERE tab_Scripts.Sc_Index = " & form_ScriptIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Script updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Script.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Script", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                If IsDBNull(ScNotes) Then
                                                    ScNotes = ""
                                                End If
                                                If ScNotes <> form_Notes Then
                                                    UpdateTableRecord("UPDATE tab_Scripts SET tab_Scripts.Sc_Notes = '" & Replace(form_Notes, "'", "''") & "' WHERE tab_Scripts.Sc_Index = " & form_ScriptIndex & ";")
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Notes updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Notes.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Admin", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                    End If

                                End If  ' form_Method = "StoreMe"

                                sSqlString = "SELECT * FROM tab_Scripts WHERE Tab_Scripts.Sc_Index = " & form_ScriptIndex & ";"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        ScLocationIndex = -1
                                        Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Script, Index " & form_ScriptIndex & " not found in database.</font></p>")
                                    Else
                                        ' multiple nVarChar(MAX) fields in sSqlString need the fields stored to variables sequentially
                                        ScIndex = sqlDataReader.Item("Sc_Index")
                                        ScReasonIndex = sqlDataReader.Item("Sc_ReasonIndex")
                                        ScLocationIndex = sqlDataReader.Item("Sc_LocationIndex")
                                        ScDetails = sqlDataReader.Item("Sc_Details")
                                        ScNotes = sqlDataReader.Item("Sc_Notes")
                                        If IsDBNull(ScDetails) Then
                                            ScDetails = ""
                                        End If
                                        If IsDBNull(ScNotes) Then
                                            ScNotes = "Edit by " & Me.UserName & " on " & theDate
                                        End If
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<Table cellspacing=""0"">")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit a Script</th></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Index&nbsp;</td><td colspan=""2"">" & form_ScriptIndex & "</td>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Location&nbsp;</td>")
                                        If ScLocationIndex = 0 Then
                                            Response_WriteLine("<td>--- Default ---</td>")
                                        Else
                                            Response_WriteLine("<td>" & Me.GetLocationName(ScLocationIndex) & "")
                                            Response_WriteLine("<form name=""frmLinkEditLocationFromES"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0;display:inline;"">")
                                            Response_WriteLine("<a class=""submitAsLink"" onclick=""javascript:frmLinkEditLocationFromES.submit()""><small>Edit</small></a>")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & ScLocationIndex & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</td>")
                                        End If
                                        Response_WriteLine("<td>Cannot associate to different Location.<br>")
                                        Response_WriteLine("Must instead create a new Script under a new Location.</td></tr>")
                                        Response_WriteLine("<tr bgcolor=""#eeeeee"" valign=""top""><td align=""right"">Reason&nbsp;</td>")
                                        Response_WriteLine("<td>" & Me.GetReasonFromScriptIndex(form_ScriptIndex) & "</td>")
                                        Response_WriteLine("<td>Cannot associate to different Reason.<br>")
                                        Response_WriteLine("Must instead create a new Script under a new Reason.</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<form name=""form_Method_EditScript"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditScript"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_ScriptIndex"" value=""" & form_ScriptIndex & """>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Script&nbsp;</td>")
                                        Response_WriteLine("<td><textarea name=""form_Details"" class=""form-control"" rows=""4"" cols=""80"">" & ScDetails & "</textarea></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Enter the Script as it will be read back to the caller</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes&nbsp;</td>")
                                        Response_WriteLine("<td><input type=""text"" name=""form_Notes"" size=""40"" class=""form-control"" value=""" & Replace(ScNotes, """", "&#34;") & """ maxlength=""255""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Any comment that may be useful to explain the Script</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Save Changes to Script""></center></td></tr>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</Table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowScriptsTable(ScLocationIndex)

                            Case "EditHoliday"
                                Dim form_OriginalHoDate
                                ' Original HoDate is needed as it's the "Unique Field" in access and it has the chance of being changed.
                                form_OriginalHoDate = Request.Form("form_OriginalHoDate")

                                If form_Method = "StoreMe" Then
                                    ' new EditHoliday fields submitted, store them

                                    form_Error = ""
                                    If form_HoDate = "" Then
                                        form_Error = form_Error & " Date"
                                    Else
                                        If Not IsDate(form_HoDate) Then
                                            form_Error = form_Error & " valid-Date"
                                        End If
                                    End If
                                    If form_Name = "" Then
                                        form_Error = form_Error & " Name"
                                    End If
                                    If form_Error = "" Then
                                        ' safe to update
                                        form_HoDate = CDate(form_HoDate)

                                        ' #date# for access, 'date' for sSqlString
                                        If _clsMessageVAR.BUsesSqlString = True Then
                                            sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = '" & form_OriginalHoDate & "';"
                                        Else
                                            sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = #" & form_OriginalHoDate & "#;"
                                        End If

                                        MyCommand.CommandText = sSqlString

                                        Try
                                            If MyConnection.State = ConnectionState.Closed Then
                                                MyConnection.Open()
                                            End If

                                            sqlDataReader = MyCommand.ExecuteReader

                                            If Not sqlDataReader.Read Then
                                                Response_WriteLine("<p><font color=""red"">Error - <i>" & form_OriginalHoDate & "</i> not found in database.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            Else
                                                If sqlDataReader.Item("Ho_Date") <> form_HoDate Then
                                                    ' #date# for access, 'date' for sSqlString
                                                    If _clsMessageVAR.BUsesSqlString = True Then
                                                        UpdateTableRecord("UPDATE tab_Holidays SET tab_Holidays.Ho_Date= '" & form_HoDate & "' WHERE tab_Holidays.Ho_Date = '" & form_OriginalHoDate & "';")
                                                    Else
                                                        UpdateTableRecord("UPDATE tab_Holidays SET tab_Holidays.Ho_Date= #" & form_HoDate & "# WHERE tab_Holidays.Ho_Date = #" & form_OriginalHoDate & "#;")
                                                    End If
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Holiday Date updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Holiday Date.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Holiday", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                ' do this 1 with new form_HoDate as it relies on unique field Ho_Date
                                                If sqlDataReader.Item("Ho_Name") <> form_Name Then
                                                    ' #date# for access, 'date' for sSqlString
                                                    If _clsMessageVAR.BUsesSqlString = True Then
                                                        UpdateTableRecord("UPDATE tab_Holidays SET tab_Holidays.Ho_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Holidays.Ho_Date = '" & form_HoDate & "';")
                                                    Else
                                                        UpdateTableRecord("UPDATE tab_Holidays SET tab_Holidays.Ho_Name = '" & Replace(form_Name, "'", "''") & "' WHERE tab_Holidays.Ho_Date = #" & form_HoDate & "#;")
                                                    End If
                                                    'On Error Resume Next
                                                    If Err.Number = 0 Then
                                                        Response_WriteLine("<p><font color=""green"">Holiday Name updated successfully.</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR updating Holiday Name.</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If
                                                    'On Error GoTo 0

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Edit Holiday", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If
                                                Else
                                                    ' skip, not changed
                                                End If

                                                ' reset Application Variable to force Holiday reload
                                                Application("Ho.CrDate") = DateAdd("d", -1, theDate)
                                            End If

                                        Catch ex As Exception
                                            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                        Finally
                                            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                        End Try

                                    Else
                                        ' missing info, try again
                                        Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                        ' update query field back to the original since it wasn't changed
                                        form_HoDate = form_OriginalHoDate
                                    End If

                                End If  ' form_Method = "StoreMe"

                                ' #date# for access, 'date' for sSqlString
                                If _clsMessageVAR.BUsesSqlString = True Then
                                    sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = '" & form_HoDate & "';"
                                Else
                                    sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = #" & form_HoDate & "#;"
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        Response_WriteLine("<p><font color=""red"">ERROR - cannot edit Holiday, """ & form_HoDate & """ not found in database.</font></p>")
                                    Else
                                        Response_WriteLine("<p>")
                                        Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                        Response_WriteLine("<Table cellspacing=""0"">")
                                        Response_WriteLine("<form name=""form_Method_EditHoliday"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditHoliday"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                        Response_WriteLine("<input type=""hidden"" name=""form_OriginalHoDate"" value=""" & form_HoDate & """>")
                                        Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""3"">Edit a Holiday</th></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Date&nbsp;</td>")
                                        Response_WriteLine("<td><input type=""text"" name=""form_HoDate"" class=""form-control"" value=""" & form_HoDate & """ size=""10"" maxlength=""10""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">MM/DD/YYYY</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3"">&nbsp;</td></tr>")
                                        Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Holiday Name&nbsp;</td>")
                                        Response_WriteLine("<td><input type=""text"" name=""form_Name"" class=""form-control"" value=""" & Replace(sqlDataReader.Item("Ho_Name"), """", "&#34;") & """ size=""40"" maxlength=""50""></td>")
                                        Response_WriteLine("<td bgcolor=""#eeeeee"">Follow naming style as seen on OPM.gov.  Open in new window:<br>")
                                        Response_WriteLine("<a href=""http://www.opm.gov/operating_status_schedules/fedhol/"" target=""_blank"">http://www.opm.gov/operating_status_schedules/fedhol/</a><br>")
                                        Response_WriteLine("</td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                        Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Save Changes to Holiday""></center></td></tr>")
                                        Response_WriteLine("</form>")
                                        Response_WriteLine("</Table>")
                                        Response_WriteLine("</td></tr></table>")
                                        Response_WriteLine("</p>")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowHolidaysTable()

                            Case "RemoveSite"
                                ' form_SiteNum guaranteed to exist, unless user hits Refresh after already removing
                                safeAction = ""
                                form_Name = Me.GetSiteName(form_SiteNum)

                                form_Error = ""
                                If form_Name = "" Then
                                    form_Error = "Error: Site Name not found.<br>"
                                End If

                                If form_Error = "" Then
                                    ' 1st check for ANY (OPEN or closed) Messages for this Location
                                    '   if ANY exist, cannot delete.  This is because Messages are tied to the unique SiteNum of this site.
                                    '   You can instead replace the Site with something else
                                    '   and the new name will inherit the old site's Message history
                                    ' 2nd check for ANY (active or inactive) locations that are members of this site.
                                    '   if ANY exist, cannot yet delete.  Must first remove the locations.

                                    ' 1st check for ANY (OPEN or closed) Messages for this Site
                                    sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages WHERE tab_Messages.Msg_SiteNum = '" & form_SiteNum & "';"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = True Then
                                            thecount = sqlDataReader.Item("THECOUNT")

                                            If thecount > 0 Then
                                                ' if ANY Messages exist
                                                '	then safeAction = "CannotRemove"
                                                safeAction = "CannotRemove"
                                                safeValue = thecount
                                            End If

                                            ' 2nd check for ANY (active or inactive) locations that are members of this site.
                                            If safeAction = "" Then
                                                sSqlString = "SELECT COUNT(tab_Locations.Lo_Index) AS THECOUNT FROM tab_Locations WHERE tab_Locations.Lo_SiteNum = '" & form_SiteNum & "';"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If sqlDataReader2.Read = True Then
                                                        thecount = sqlDataReader2.Item("THECOUNT")

                                                        If thecount > 0 Then
                                                            ' if ANY Messages exist
                                                            '	then safeAction = "CannotRemove"
                                                            ' site still has Locations
                                                            safeAction = "LocationsExist"
                                                            safeValue = thecount
                                                        Else
                                                            ' good, no active Locations!
                                                            safeAction = "Remove"
                                                        End If
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    Select Case safeAction
                                        Case "CannotRemove"
                                            '   cannot delete.  This is because Messages are tied to the unique SiteNum of this site.
                                            '   You can instead replace the Site with something else
                                            '   and the new name will inherit the old site's Message history
                                            Response_WriteLine("<p><table>")
                                            Response_WriteLine("<tr><td><font color=""red"">Unable To Remove Site " & form_SiteNum & " - " & form_Name & "</font>:<br>")
                                            If safeValue = 1 Then
                                                Response_WriteLine("There is 1 Message associated with this Site.<br>")
                                            Else
                                                Response_WriteLine("There are " & safeValue & " Messages associated with this Site.<br>")
                                            End If
                                            Response_WriteLine("Messages are tied to the SiteNum.<br>")
                                            Response_WriteLine("Suggestion: You can instead replace the Site with something else<br>")
                                            Response_WriteLine("and the new Site will inherit the old Site's Message history.")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td><center>")
                                            Response_WriteLine("<form name=""frmChoiceEditSite2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditSite"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_SiteNum"" value=""" & form_SiteNum & """>")
                                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Site " & form_SiteNum & " - " & Replace(form_Name, """", "&#34;") & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</center></td></tr>")
                                            Response_WriteLine("</table></p>")
                                        Case "LocationsExist"
                                            ' Locations exist.  Must first remove the tab_Locations.
                                            Response_WriteLine("<p><table><tr><td>")
                                            If safeValue = 1 Then
                                                Response_WriteLine("<font color=""red"">Site " & form_SiteNum & " - " & form_Name & " still has 1 location:</font><br>")
                                            Else
                                                Response_WriteLine("<font color=""red"">Site " & form_SiteNum & " - " & form_Name & " still has " & safeValue & " locations:</font><br>")
                                            End If
                                            Response_WriteLine("Suggestion: Remove all the locations for this site before removing the site.")
                                            Response_WriteLine("</td></tr></table></p>")
                                        Case "Remove"
                                            ' before deleting, move to end of sort order (it adjusts existing site siteorder so there isn't a gap)
                                            Me.ReSortSite(form_SiteNum, "ZZZ")

                                            If _clsMessageVAR.BUsesSqlString = True Then
                                                sSqlString = "DELETE FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & form_SiteNum & "';"
                                            Else
                                                sSqlString = "DELETE * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & form_SiteNum & "';"
                                            End If

                                            If DeleteTableRecord(sSqlString) Then
                                                Response_WriteLine("<p><font color=""green"">Site " & form_SiteNum & " - " & form_Name & " removed from the system.</font></p>")
                                            Else
                                                Response_WriteLine("<p><font color=""red"">ERROR attempting to remove Site " & form_SiteNum & " - " & form_Name & "</font></p>")
                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                            End If

                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                            errstore = Me.StoreAuditAdmin("Remove Site", sSqlString)
                                            If errstore <> "Success" Then
                                                Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                            End If

                                        Case Else
                                            Response_WriteLine("<p><font color=""red"">Error: Remove Site situation not identified.</font></p>")
                                    End Select
                                Else
                                    Response_WriteLine("<p><font color=""red"">" & form_Error & "")
                                    Response_WriteLine("Possible cause = did you hit refresh after already removing the Site?<br>")
                                    Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                End If
                                Me.ShowSitesTable(form_SiteNum)

                            Case "RemoveLocation"
                                ' form_LocationIndex guaranteed to exist, unless user hits Refresh after already removing
                                safeAction = ""
                                form_Name = Me.GetLocationName(form_LocationIndex)
                                form_SiteNum = Me.GetSiteNum(form_LocationIndex)

                                form_Error = ""
                                If form_Name = "" Then
                                    form_Error = "Error: Location Name not found.<br>"
                                End If
                                If form_SiteNum = "" Then
                                    form_Error = form_Error & "Error: Location's Site not found.<br>"
                                End If

                                If form_Error = "" Then
                                    ' 1st check for ANY (OPEN or closed) Messages for this Location
                                    '   if ANY exist, cannot delete.  This is because Messages are tied to the unique index of this Location.
                                    '   You can instead replace the Location name with something else
                                    '   and the new name will inherit the old Location's Message history
                                    ' 2nd check for ANY (active or inactive) Teams that are members of this Location.
                                    '   if ANY exist, cannot yet delete.  Must first remove the Teams.

                                    ' 1st check for ANY (OPEN or closed) Messages for this Location
                                    sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages WHERE tab_Messages.Msg_LocationIndex = " & form_LocationIndex & ";"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = True Then
                                            thecount = sqlDataReader.Item("THECOUNT")

                                            If thecount > 0 Then
                                                ' if ANY Messages exist
                                                '	then safeAction = "CannotRemove"
                                                safeAction = "CannotRemove"
                                                safeValue = thecount
                                            End If

                                            ' 2nd check for ANY (active or inactive) Teams that are members of this Location.
                                            If safeAction = "" Then
                                                sSqlString = "SELECT COUNT(tab_Teams.Te_Index) AS THECOUNT FROM tab_Teams WHERE tab_Teams.Te_LocationIndex = " & form_LocationIndex & ";"
                                                If _clsMessageVAR.BDebug = True Then
                                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                                End If

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If sqlDataReader2.Read = True Then
                                                        thecount = sqlDataReader2.Item("THECOUNT")

                                                        If thecount > 0 Then
                                                            ' if ANY Messages exist
                                                            '	then safeAction = "CannotRemove"
                                                            ' Location still has Teams
                                                            safeAction = "TeamsExist"
                                                            safeValue = thecount
                                                        Else
                                                            ' good, no active Teams!
                                                            safeAction = "Remove"
                                                        End If
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    Select Case safeAction
                                        Case "CannotRemove"
                                            ' cannot delete.  This is because Messages are tied to the unique index of this Team.
                                            '   You can instead replace the Team name with something else
                                            '   and the new name will inherit the old Team's Message history
                                            Response_WriteLine("<p><table>")
                                            Response_WriteLine("<tr><td><font color=""red"">Unable To Remove Location " & form_Name & "</font>:<br>")
                                            If safeValue = 1 Then
                                                Response_WriteLine("There is 1 Message associated with this location.<br>")
                                            Else
                                                Response_WriteLine("There are " & safeValue & " Messages associated with this location.<br>")
                                            End If
                                            Response_WriteLine("Messages are tied to the unique index of the location.<br>")
                                            Response_WriteLine("Suggestion: You can instead replace the Location Name with something else<br>")
                                            Response_WriteLine("and the new name will inherit the old location's Message history.")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td><center>")
                                            Response_WriteLine("<form name=""frmChoiceEditLocation2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditLocation"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_LocationIndex"" value=""" & form_LocationIndex & """>")
                                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Location " & Replace(form_Name, """", "&#34;") & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</center></td></tr>")
                                            Response_WriteLine("</table></p>")
                                        Case "TeamsExist"
                                            ' Teams exist.  Must first remove the tab_Teams.
                                            Response_WriteLine("<p><table><tr><td>")
                                            If safeValue = 1 Then
                                                Response_WriteLine("<font color=""red"">Location " & form_Name & " still has 1 Team:</font><br>")
                                            Else
                                                Response_WriteLine("<font color=""red"">Location " & form_Name & " still has " & safeValue & " Teams:</font><br>")
                                            End If
                                            Response_WriteLine("Suggestion: Remove all the Teams for this location before removing the location.")
                                            Response_WriteLine("</td></tr></table></p>")
                                        Case "Remove"
                                            ' before deleting, move to end of sort order (it adjusts existing Location sortorder so there isn't a gap)
                                            Me.ReSortLocation(form_LocationIndex, "ZZZ")

                                            If _clsMessageVAR.BUsesSqlString = True Then
                                                sSqlString = "DELETE FROM tab_Locations WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";"
                                            Else
                                                sSqlString = "DELETE * FROM tab_Locations WHERE tab_Locations.Lo_Index = " & form_LocationIndex & ";"
                                            End If

                                            If DeleteTableRecord(sSqlString) Then
                                                Response_WriteLine("<p><font color=""green"">Location " & form_Name & " removed from Site")
                                                Response_WriteLine("" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & ".</font></p>")
                                            Else
                                                Response_WriteLine("<p><font color=""red"">ERROR attempting to remove Location " & form_Name & " from Site")
                                                Response_WriteLine("" & form_SiteNum & " - " & Me.GetSiteName(form_SiteNum) & ".</font></p>")
                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                            End If

                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                            errstore = Me.StoreAuditAdmin("Remove Location", sSqlString)
                                            If errstore <> "Success" Then
                                                Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                            End If

                                        Case Else
                                            Response_WriteLine("<p><font color=""red"">Error: Remove Location situation not identified.</font></p>")
                                    End Select
                                Else
                                    Response_WriteLine("<p><font color=""red"">" & form_Error & "")
                                    Response_WriteLine("Possible cause = did you hit refresh after already removing the Location?<br>")
                                    Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                End If
                                Me.ShowLocationsTable(form_SiteNum)

                            Case "RemoveTeam"
                                ' form_TeamIndex guaranteed to exist, unless user hits Refresh after already removing
                                safeAction = ""
                                form_Name = Me.GetTeamName(form_TeamIndex)
                                form_LocationIndex = Me.GetLocationIndex(form_TeamIndex)

                                form_Error = ""
                                If form_Name = "" Then
                                    form_Error = "Error: Team Name not found.<br>"
                                End If
                                If form_LocationIndex.ToString = "" Then
                                    form_Error = form_Error & "Error: Team's Location not found.<br>"
                                End If

                                If form_Error = "" Then
                                    ' 1st check for ANY (OPEN or closed) Messages for this Team
                                    '   if ANY exist, cannot delete.  This is because Messages are tied to the unique index of this Team.
                                    '   You can instead replace the Team name with something else
                                    '   and the new name will inherit the old Team's Message history
                                    ' 2nd check for ANY (active or inactive) members that are members of this Team.
                                    '   if ANY exist, cannot yet delete.  Must first remove the members.

                                    ' 1st check for ANY (OPEN or closed) Messages for this Team
                                    sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages WHERE tab_Messages.Msg_TeamIndex = " & form_TeamIndex & ";"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = True Then
                                            thecount = sqlDataReader.Item("THECOUNT")

                                            If thecount > 0 Then
                                                ' if ANY Messages exist
                                                '	then safeAction = "CannotRemove"
                                                safeAction = "CannotRemove"
                                                safeValue = thecount
                                            End If

                                            ' 2nd check for ANY (active or inactive) members that are members of this Team.
                                            If safeAction = "" Then
                                                safeValue = Me.GetTeamMemberNames(form_TeamIndex, True, False)
                                                If safeValue = "" Then
                                                    ' good, no active members!
                                                    safeAction = "Remove"
                                                Else
                                                    ' oops, still has members
                                                    safeAction = "MembersExist"
                                                End If
                                            End If

                                            Select Case safeAction
                                                Case "CannotRemove"
                                                    ' cannot delete.  This is because Messages are tied to the unique index of this Team.
                                                    '   You can instead replace the Team name with something else
                                                    '   and the new name will inherit the old Team's Message history
                                                    Response_WriteLine("<p><table>")
                                                    Response_WriteLine("<tr><td><font color=""red"">Unable To Remove Team " & form_Name & "</font>:<br>")
                                                    If safeValue = 1 Then
                                                        Response_WriteLine("There is 1 Message associated with this Team.<br>")
                                                    Else
                                                        Response_WriteLine("There are " & safeValue & " Messages associated with this Team.<br>")
                                                    End If
                                                    Response_WriteLine("Messages are tied to the unique index of the Team.<br>")
                                                    Response_WriteLine("Suggestion: You can instead replace the Team name with something else<br>")
                                                    Response_WriteLine("and the new name will inherit the old Team's Message history.")
                                                    Response_WriteLine("</td></tr>")
                                                    Response_WriteLine("<tr><td><center>")
                                                    Response_WriteLine("<form name=""frmChoiceEditTeam4"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                                    Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                                    Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                                    Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Team " & Replace(form_Name, """", "&#34;") & """>")
                                                    Response_WriteLine("</form>")
                                                    Response_WriteLine("</center></td></tr>")
                                                    Response_WriteLine("</table></p>")
                                                Case "MembersExist"
                                                    ' members exist.  Must first remove the members.
                                                    Response_WriteLine("<p><table><tr><td><font color=""red"">Team " & form_Name & " still has Members</font>:<br>")
                                                    Response_WriteLine("" & safeValue & "<br>")
                                                    Response_WriteLine("Suggestion: Remove all the Members for this Team before removing the Team.")
                                                    Response_WriteLine("</td></tr></table></p>")
                                                Case "Remove"
                                                    ' before deleting, move to end of sort order (it adjusts existing Team sortorder so there isn't a gap)
                                                    Me.ReSortTeam(form_TeamIndex, "ZZZ")

                                                    If _clsMessageVAR.BUsesSqlString = True Then
                                                        sSqlString = "DELETE FROM tab_Teams WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";"
                                                    Else
                                                        sSqlString = "DELETE * FROM tab_Teams WHERE tab_Teams.Te_Index = " & form_TeamIndex & ";"
                                                    End If

                                                    If DeleteTableRecord(sSqlString) Then
                                                        Response_WriteLine("<p><font color=""green"">Team " & form_Name & " removed")
                                                        Response_WriteLine(" from Location " & Me.GetLocationName(form_LocationIndex) & ".</font></p>")
                                                    Else
                                                        Response_WriteLine("<p><font color=""red"">ERROR attempting to remove Team " & form_Name & " ")
                                                        Response_WriteLine(" from Location " & Me.GetLocationName(form_LocationIndex) & ".</font></p>")
                                                        Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                    End If

                                                    ' StoreAuditAdmin(AA_Action, AA_Details)
                                                    errstore = Me.StoreAuditAdmin("Remove Team", sSqlString)
                                                    If errstore <> "Success" Then
                                                        Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                    End If

                                                Case Else
                                                    Response_WriteLine("<p><font color=""red"">Error: Remove Team situation not identified.</font></p>")
                                            End Select
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                Else
                                    Response_WriteLine("<p><font color=""red"">" & form_Error & "")
                                    Response_WriteLine("Possible cause = did you hit refresh after already removing the Team?<br>")
                                    Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                End If
                                Me.ShowTeamsTable(form_LocationIndex)

                            Case "RemoveMember"
                                ' form_MemberIndex passed in from form, but will not exist if user hits refresh as it was alredy deleted
                                form_Username = Me.GetMemberUsername(form_MemberIndex)
                                form_TeamIndex = Me.GetTeamIndex(form_MemberIndex)
                                form_Name = Me.GetTeamName(form_TeamIndex)
                                safeAction = ""

                                form_Error = ""
                                If form_Username = "" Then
                                    form_Error = "Error: Member Username does not exist.<br>"
                                End If
                                If form_TeamIndex.ToString = "" Then
                                    form_Error = form_Error & "Error: Team Index does not exist for this Member Index.<br>"
                                End If

                                If form_Error = "" Then
                                    ' check for ANY OPEN Messages assigned to this member
                                    ' (Closed Assigned Messages don't matter,  Me.UserName  is logged for prosperity)
                                    '   if (OPEN Assigned Messages) exist
                                    '	  then safeAction = "SuggestResolveMessages"
                                    '	  (suggest that that team resolve or reassign those Messages before removing member)
                                    '   else (OPEN Assigned Messages do not exist)
                                    '	  check Team to ensure there are other Active members.
                                    '		 if Team InActive
                                    '			then safeAction = "Remove"
                                    '		 if Team Active
                                    '			if other members Active
                                    '			   safeAction = "Remove"
                                    '			if no other members
                                    '			   safeAction = "SuggestAddressTeam"

                                    ' check for ANY OPEN Messages assigned to this member
                                    ' (Closed Assigned Messages don't matter,  Me.UserName  is logged for prosperity)
                                    sSqlString = "SELECT COUNT(tab_Messages.Msg_Index) AS THECOUNT FROM tab_Messages" & " WHERE tab_Messages.Msg_Assigned LIKE '" & Replace(form_Username, "'", "''") & "'" & " AND tab_Messages.Msg_TeamIndex = " & form_TeamIndex & " AND tab_Messages.Msg_Completed IS NULL;"
                                    If _clsMessageVAR.BDebug = True Then
                                        Response.Write("sSqlString=" & sSqlString & "<br>")
                                    End If

                                    MyCommand.CommandText = sSqlString

                                    Try
                                        If MyConnection.State = ConnectionState.Closed Then
                                            MyConnection.Open()
                                        End If

                                        sqlDataReader = MyCommand.ExecuteReader

                                        If sqlDataReader.Read = True Then
                                            thecount = sqlDataReader.Item("THECOUNT")

                                            If thecount > 0 Then
                                                ' if (OPEN Assigned Messages) exist
                                                '	then safeAction = "SuggestResolveMessages"
                                                safeAction = "SuggestResolveMessages"
                                                safeValue = thecount
                                            End If

                                            If safeAction = "" Then
                                                ' else (OPEN Assigned Messages do not exist)
                                                ' check Team to ensure there are other Active members.
                                                sSqlString = "SELECT COUNT(tab_Members.Me_Index) AS THECOUNT FROM tab_Members" & " WHERE tab_Members.Me_TeamIndex = " & form_TeamIndex & " AND tab_Members.Me_Username NOT LIKE '" & Replace(form_Username, "'", "''") & "'" & " AND tab_Members.Me_Active = 'Yes';"

                                                MyCommand2.CommandText = sSqlString

                                                Try
                                                    If MyConnection2.State = ConnectionState.Closed Then
                                                        MyConnection2.Open()
                                                    End If

                                                    sqlDataReader2 = MyCommand2.ExecuteReader

                                                    If sqlDataReader2.Read = True Then
                                                        thecount = sqlDataReader2.Item("THECOUNT")

                                                        If thecount > 0 Then
                                                            ' there are other active members
                                                            ' safe to remove the member
                                                            safeAction = "Remove"
                                                        Else
                                                            ' all members are inactive
                                                            ' check if Team InActive
                                                            sSqlString = "SELECT tab_Teams.Te_Active FROM tab_Teams WHERE tab_Teams.Te_Index = " & form_TeamIndex & " AND tab_Teams.Te_Active = 'No';"

                                                            MyCommand3.CommandText = sSqlString

                                                            Try
                                                                If MyConnection3.State = ConnectionState.Closed Then
                                                                    MyConnection3.Open()
                                                                End If

                                                                sqlDataReader3 = MyCommand3.ExecuteReader

                                                                If Not sqlDataReader3.HasRows Then
                                                                    ' Team is Active but has no other active members.
                                                                    safeAction = "SuggestAddressTeam"
                                                                Else
                                                                    ' found this Team inactive
                                                                    ' safe to remove the member
                                                                    safeAction = "Remove"
                                                                End If

                                                            Catch ex As Exception
                                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                            Finally
                                                                If MyConnection3.State = ConnectionState.Open Then MyConnection3.Close()
                                                                If (Not sqlDataReader3 Is Nothing) Then sqlDataReader3.Close()
                                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                            End Try

                                                        End If
                                                    End If

                                                Catch ex As Exception
                                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                                Finally
                                                    If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                    If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                                End Try

                                            End If
                                        End If

                                    Catch ex As Exception
                                        System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                    Finally
                                        If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                        If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                        If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                    End Try

                                    Select Case safeAction
                                        Case "SuggestResolveMessages"
                                            ' (suggest that that team resolve or reassign those Messages before removing member)
                                            Response_WriteLine("<p><table><tr><td><font color=""red"">Unable To Remove Member " & form_Username & "</font>:<br>")
                                            If safeValue = 1 Then
                                                Response_WriteLine("There is 1 Open Assigned Message.<br>")
                                            Else
                                                Response_WriteLine("There are " & safeValue & " Open Assigned Messages.<br>")
                                            End If
                                            Response_WriteLine("Suggestion: Resolve by re-assigning or closing then try removing this Member again.<br>")
                                            Response_WriteLine("Or you can instead replace the Member with something else<br>")
                                            Response_WriteLine("and the new Member will inherit the old Member's assignments.<br>")
                                            Response_WriteLine("<form name=""frmChoiceEditMember2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditMember"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_MemberIndex"" value=""" & form_MemberIndex & """>")
                                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Member " & form_Username & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</td></tr></table></p>")
                                        Case "SuggestAddressTeam"
                                            Response_WriteLine("<p><table>")
                                            Response_WriteLine("<tr><td><font color=""red"">Unable to Remove Member " & form_Username & "</font>:<br>")
                                            Response_WriteLine("The Team " & form_Name & " is still active but there are no other active members.<br>")
                                            Response_WriteLine("Resolve by Inactivating the Team, toggling inactive members to active, or add other active members.<br>")
                                            Response_WriteLine("Then try removing this Member again.")
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td><center>")
                                            Response_WriteLine("<form name=""frmChoiceEditTeam2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""EditTeam"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Edit Team " & Replace(form_Name, """", "&#34;") & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("<br>")
                                            Response_WriteLine("<form name=""frmChoiceAddMember2"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""AddMember"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_TeamIndex"" value=""" & form_TeamIndex & """>")
                                            Response_WriteLine("<input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Add Member to Team " & Replace(form_Name, """", "&#34;") & """>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</center></td></tr>")
                                            Response_WriteLine("</table></p>")
                                        Case "Remove"
                                            ' before deleting, move to end of sort order (it adjusts existing Team sortorder so there isn't a gap)
                                            Me.ReSortMember(form_MemberIndex, "ZZZ")

                                            If _clsMessageVAR.BUsesSqlString = True Then
                                                sSqlString = "DELETE FROM tab_Members WHERE tab_Members.Me_Index = " & form_MemberIndex & ";"
                                            Else
                                                sSqlString = "DELETE * FROM tab_Members WHERE tab_Members.Me_Index = " & form_MemberIndex & ";"
                                            End If

                                            If DeleteTableRecord(sSqlString) Then
                                                Response_WriteLine("<p><font color=""green"">Member " & form_Username & " removed")
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine(" from Team " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & ".</font></p>")
                                                Else
                                                    Response_WriteLine(" from Team " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & ".</font></p>")
                                                End If
                                            Else
                                                Response_WriteLine("<p><font color=""red"">ERROR attempting to remove Member " & form_Username & " ")
                                                If _clsMessageVAR.Gl_overrideTeamColorize = True Then
                                                    Response_WriteLine(" from Team " & Me.ColorizeTeamName(Me.GetTeamName(form_TeamIndex)) & ".</font></p>")
                                                Else
                                                    Response_WriteLine(" from Team " & Me.ColorizeFont(Me.GetTeamName(form_TeamIndex)) & ".</font></p>")
                                                End If
                                                Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                            End If

                                            ' StoreAuditAdmin(AA_Action, AA_Details)
                                            errstore = Me.StoreAuditAdmin("Remove Member", sSqlString)
                                            If errstore <> "Success" Then
                                                Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                            End If

                                        Case Else
                                            Response_WriteLine("<p><font color=""red"">Error: Remove Member situation not identified.</font></p>")
                                    End Select
                                Else
                                    Response_WriteLine("<p><font color=""red"">" & form_Error & "")
                                    Response_WriteLine("Possible cause = did you hit refresh after already removing the Member?<br>")
                                    Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                End If

                                ' 000 admins will default to this username's table
                                Me.ShowMembersTable(0, form_Username)

                            Case "RemoveAdmin"
                                sSqlString = "SELECT * FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If sqlDataReader.Read = False Then
                                        ' removal already took place
                                        Response_WriteLine("<p><font color=""red"">Error: Admin not found, did you already remove it and then hit refresh?<br>")
                                        Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                    Else
                                        If form_Method = "StoreMe" Then
                                            ' RemoveAdmin submitted, Delete it
                                            form_Error = ""
                                            If form_Username = "" Then
                                                form_Error = form_Error & " Username"
                                            End If
                                            If form_Error = "" Then
                                                ' safe to delete
                                                If _clsMessageVAR.BUsesSqlString = True Then
                                                    sSqlString = "DELETE FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';"
                                                Else
                                                    sSqlString = "DELETE * FROM tab_Admins WHERE tab_Admins.Adm_Username LIKE '" & Replace(form_Username, "'", "''") & "';"
                                                End If

                                                If DeleteTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">Success.  Removed " & form_Username & " from Admins table.</font></p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">Error.  Unable to Remove " & form_Username & " from Admins table.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Remove Admin", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' missing info, try again
                                                Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".<br>")
                                                Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                            End If
                                        Else

                                            ' #date# for access, 'date' for sSqlString
                                            If _clsMessageVAR.BUsesSqlString = True Then
                                                sSqlString = "SELECT * FROM tab_AuditAdmin WHERE tab_AuditAdmin.AA_Username LIKE '" & Replace(form_Username, "'", "''") & "' AND tab_AuditAdmin.AA_Dt >= '" & (DateAdd("m", -1, theDate)) & "';"
                                            Else
                                                sSqlString = "SELECT * FROM tab_AuditAdmin WHERE tab_AuditAdmin.AA_Username LIKE '" & Replace(form_Username, "'", "''") & "' AND tab_AuditAdmin.Au_Dt >= #" & (DateAdd("m", -1, theDate)) & "#;"
                                            End If
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("sSqlString=" & sSqlString & "<br>")
                                            End If

                                            MyCommand2.CommandText = sSqlString

                                            Try
                                                If MyConnection2.State = ConnectionState.Closed Then
                                                    MyConnection2.Open()
                                                End If

                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                If Not sqlDataReader2.HasRows Then
                                                    Response_WriteLine("<p><table><tr><td><font color=""green"">")
                                                    Response_WriteLine("Note - This Admin has NOT made any entries in the Admin Audit table within the last month.<br>")
                                                    Response_WriteLine("It is likely safe to remove this Admin from the system.")
                                                    Response_WriteLine("</font></td></tr></table></p>")
                                                Else
                                                    Response_WriteLine("<p><table><tr><td><font color=""red"">")
                                                    Response_WriteLine("Note - This Admin has entries in the Admin Audit table within the last month<br>")
                                                    Response_WriteLine("It is questionable if it is really safe to remove this Admin from the system:<br>")
                                                    While sqlDataReader2.Read = True
                                                        Response_WriteLine("&nbsp;&nbsp;&nbsp;" & sqlDataReader2.Item("AA_Action") & " on " & sqlDataReader2.Item("AA_Dt") & "<br>")
                                                    End While
                                                    Response_WriteLine("</font></td></tr></table></p>")
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                            ' #date# for access, 'date' for sSqlString
                                            If _clsMessageVAR.BUsesSqlString = True Then
                                                sSqlString = "SELECT * FROM tab_Audit WHERE tab_Audit.Au_Username LIKE '" & Replace(form_Username, "'", "''") & "' AND tab_Audit.Au_Dt >= '" & (DateAdd("m", -1, theDate)) & "';"
                                            Else
                                                sSqlString = "SELECT * FROM tab_Audit WHERE tab_Audit.Au_Username LIKE '" & Replace(form_Username, "'", "''") & "' AND tab_Audit.Au_Dt >= #" & (DateAdd("m", -1, theDate)) & "#;"
                                            End If
                                            If _clsMessageVAR.BDebug = True Then
                                                Response.Write("sSqlString=" & sSqlString & "<br>")
                                            End If

                                            MyCommand2.CommandText = sSqlString

                                            Try
                                                If MyConnection2.State = ConnectionState.Closed Then
                                                    MyConnection2.Open()
                                                End If

                                                sqlDataReader2 = MyCommand2.ExecuteReader

                                                If Not sqlDataReader2.HasRows Then
                                                    Response_WriteLine("<p><table><tr><td><font color=""green"">")
                                                    Response_WriteLine("Note - This Admin has NOT made any entries in the Message Audit table within the last month.<br>")
                                                    Response_WriteLine("It is likely safe to remove this Admin from the system.")
                                                    Response_WriteLine("</font></td></tr></table></p>")
                                                Else
                                                    Response_WriteLine("<p><table><tr><td><font color=""navy"">")
                                                    Response_WriteLine("Note - This Admin has entries in the Message Audit table within the last month<br>")
                                                    Response_WriteLine("It is questionable if it is really safe to remove this Admin from the system:<br>")
                                                    While sqlDataReader2.Read = True
                                                        Response_WriteLine("&nbsp;&nbsp;&nbsp;" & sqlDataReader2.Item("Au_IndexMessage") & ": " & sqlDataReader2.Item("Au_Action") & " on " & sqlDataReader2.Item("Au_Dt") & "<br>")
                                                    End While
                                                    Response_WriteLine("</font></td></tr></table></p>")
                                                End If

                                            Catch ex As Exception
                                                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                            Finally
                                                If MyConnection2.State = ConnectionState.Open Then MyConnection2.Close()
                                                If (Not sqlDataReader2 Is Nothing) Then sqlDataReader2.Close()
                                                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                            End Try

                                            Response_WriteLine("<p>")
                                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                            Response_WriteLine("<table cellspacing=""0"">")
                                            Response_WriteLine("<form name=""form_Method_RemoveAdmin"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveAdmin"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Username"" value=""" & form_Username & """>")
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""2"">Remove an Admin</th></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Name</td><td>" & sqlDataReader.Item("Adm_Name") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Username</td><td>" & sqlDataReader.Item("Adm_Username") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Username</td><td>" & sqlDataReader.Item("Adm_SID") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Email</td><td>" & sqlDataReader.Item("Adm_Email") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum</td><td>" & sqlDataReader.Item("Adm_SiteNum") & "-" & Me.GetSiteName(sqlDataReader.Item("Adm_SiteNum")) & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Access</td><td>" & sqlDataReader.Item("Adm_AccessLevel") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type</td><td>" & sqlDataReader.Item("Adm_Type") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">FlagOn</td><td>" & sqlDataReader.Item("Adm_FlagOn") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes</td><td>" & sqlDataReader.Item("Adm_Notes") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Admin Now""></center></td></tr>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</table>")
                                            Response_WriteLine("</td></tr></table>")
                                            Response_WriteLine("</p>")
                                        End If
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowAdminsTable(form_Username)

                            Case "RemoveADGroup"
                                sSqlString = "SELECT * FROM tab_ADGroups WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        ' removal already took place
                                        Response_WriteLine("<p><font color=""red"">Error: Group not found, did you already remove it and then hit refresh?<br>")
                                        Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                    Else
                                        If form_Method = "StoreMe" Then
                                            ' RemoveADGroup submitted, Delete it
                                            form_Error = ""
                                            If form_Name = "" Then
                                                form_Error = form_Error & " ADGroupName"
                                            End If
                                            If form_Error = "" Then
                                                ' safe to delete

                                                If _clsMessageVAR.BUsesSqlString = True Then
                                                    sSqlString = "DELETE FROM tab_ADGroups WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';"
                                                Else
                                                    sSqlString = "DELETE * FROM tab_ADGroups WHERE tab_ADGroups.AD_GroupName LIKE '" & Replace(form_Name, "'", "''") & "';"
                                                End If

                                                If DeleteTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">Success.  Removed " & form_Name & " from ADGroups table.</font></p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">Error.  Unable to Remove " & form_Name & " from ADGroups table.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Remove ADGroup", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' missing info, try again
                                                Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</font></p>")
                                            End If
                                        Else
                                            Response_WriteLine("<p>")
                                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                            Response_WriteLine("<table cellspacing=""0"">")
                                            Response_WriteLine("<form name=""form_Method_RemoveADGroup"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveADGroup"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Name"" value=""" & Replace(form_Name, """", "&#34;") & """>")
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""2"">Remove an AD Group</th></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">SiteNum</td><td>" & sqlDataReader.Item("AD_SiteNum") & "-" & Me.GetSiteName(sqlDataReader.Item("AD_SiteNum")) & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Access</td><td>" & sqlDataReader.Item("AD_AccessLevel") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Type</td><td>" & sqlDataReader.Item("AD_Type") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Group Name</td><td>" & sqlDataReader.Item("AD_GroupName") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove AD Group Now""></center></td></tr>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</table>")
                                            Response_WriteLine("</td></tr></table>")
                                            Response_WriteLine("</p>")
                                        End If
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowADGroupsTable(Me.AdminSite)

                            Case "RemoveScript"
                                sSqlString = "SELECT * FROM tab_Scripts WHERE tab_Scripts.Sc_Index = " & form_ScriptIndex & ";"
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        ' removal already took place
                                        Response_WriteLine("<p><font color=""red"">Error: Script not found, did you already remove it and then hit refresh?<br>")
                                        Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                    Else
                                        If form_Method = "StoreMe" Then
                                            ' RemoveScript submitted, Delete it
                                            form_Error = ""
                                            If form_ScriptIndex = "" Then
                                                form_Error = form_Error & " ScriptIndex"
                                            End If
                                            If form_Error = "" Then
                                                ' safe to delete
                                                If _clsMessageVAR.BUsesSqlString = True Then
                                                    sSqlString = "DELETE FROM tab_Scripts WHERE tab_Scripts.Sc_Index = " & form_ScriptIndex & ";"
                                                Else
                                                    sSqlString = "DELETE * FROM tab_Scripts WHERE tab_Scripts.Sc_Index = " & form_ScriptIndex & ";"
                                                End If

                                                If DeleteTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">Success.  Removed Index " & form_ScriptIndex & " from Scripts table.</font></p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">Error.  Unable to Remove " & form_ScriptIndex & " from Scripts table.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Remove Script", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' missing info, try again
                                                Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".<br>")
                                                Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                            End If
                                        Else
                                            Response_WriteLine("<p>")
                                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                            Response_WriteLine("<table cellspacing=""0"">")
                                            Response_WriteLine("<form name=""form_Method_RemoveScript"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveScript"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_ScriptIndex"" value=""" & form_ScriptIndex & """>")
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""2"">Remove a Script</th></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Location</td>")
                                            If sqlDataReader.Item("Sc_LocationIndex") = 0 Then
                                                Response_WriteLine("<td>---Default---</td>")
                                            Else
                                                Response_WriteLine("<td>" & Me.GetLocationName(sqlDataReader.Item("Sc_LocationIndex")) & "</td>")
                                            End If
                                            Response_WriteLine("</tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Reason</td><td>" & Me.GetReason(sqlDataReader.Item("Sc_ReasonIndex")) & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Script</td><td>" & sqlDataReader.Item("Sc_Details") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Notes</td><td>" & sqlDataReader.Item("Sc_Notes") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Script Now""></center></td></tr>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</table>")
                                            Response_WriteLine("</td></tr></table>")
                                            Response_WriteLine("</p>")
                                        End If
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowScriptsTable(-1)

                            Case "RemoveHoliday"
                                Dim holdDate
                                ' load oldest completed Message's Date that hasn't been purged
                                sSqlString = "SELECT TOP 1 tab_Messages.Msg_Dt FROM tab_Messages ORDER BY tab_Messages.Msg_Dt ASC;"

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If sqlDataReader.Read = False Then
                                        holdDate = "None Exist"
                                    Else
                                        holdDate = sqlDataReader.Item("Msg_Dt")
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                ' #date# for access, 'date' for sSqlString
                                If _clsMessageVAR.BUsesSqlString = True Then
                                    sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = '" & form_HoDate & "';"
                                Else
                                    sSqlString = "SELECT * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = #" & form_HoDate & "#;"
                                End If
                                If _clsMessageVAR.BDebug = True Then
                                    Response.Write("sSqlString=" & sSqlString & "<br>")
                                End If

                                MyCommand.CommandText = sSqlString

                                Try
                                    If MyConnection.State = ConnectionState.Closed Then
                                        MyConnection.Open()
                                    End If

                                    sqlDataReader = MyCommand.ExecuteReader

                                    If Not sqlDataReader.Read Then
                                        ' removal already took place
                                        Response_WriteLine("<p><font color=""red"">Error: Holiday not found, did you already remove it and then hit refresh?<br>")
                                        Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                    Else
                                        If form_Method = "StoreMe" Then
                                            ' RemoveHoliday submitted, Delete it
                                            form_Error = ""
                                            If form_HoDate = "" Then
                                                form_Error = form_Error & " Holiday Date"
                                            End If
                                            If form_Error = "" Then
                                                ' safe to delete
                                                ' #date# for access, 'date' for sSqlString
                                                If _clsMessageVAR.BUsesSqlString = True Then
                                                    sSqlString = "DELETE FROM tab_Holidays WHERE tab_Holidays.Ho_Date = '" & form_HoDate & "';"
                                                Else
                                                    sSqlString = "DELETE * FROM tab_Holidays WHERE tab_Holidays.Ho_Date = #" & form_HoDate & "#;"
                                                End If

                                                If DeleteTableRecord(sSqlString) Then
                                                    Response_WriteLine("<p><font color=""green"">Success.  Removed " & form_HoDate & " from Holidays table.</font></p>")
                                                Else
                                                    Response_WriteLine("<p><font color=""red"">Error.  Unable to Remove " & form_HoDate & " from Holidays table.</font></p>")
                                                    Me.ErrorHandler(Err.Number & ", " & Err.Description & "<br>" & sSqlString, True, False)
                                                End If

                                                ' reset Application Variable to force Holiday reload
                                                Application("Ho.CrDate") = DateAdd("d", -1, theDate)

                                                ' StoreAuditAdmin(AA_Action, AA_Details)
                                                errstore = Me.StoreAuditAdmin("Remove Holiday", sSqlString)
                                                If errstore <> "Success" Then
                                                    Response_WriteLine("<p><font color=""red"">" & errstore & "</font></p>")
                                                End If
                                            Else
                                                ' missing info, try again
                                                Response_WriteLine("<p><font color=""red"">Error - Missing " & form_Error & ".<br>")
                                                Response_WriteLine("Start over in <a href=""" & _clsMessageVAR.WebAdminURL & "?A=Setup&S=" & S & "&menu=Edit"">Edit Setup</a>.</font></p>")
                                            End If
                                        Else
                                            Response_WriteLine("<p>")
                                            Response_WriteLine("<table border=""1"" bordercolor=""black"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                                            Response_WriteLine("<table cellspacing=""0"">")
                                            Response_WriteLine("<form name=""form_Method_RemoveHoliday"" action=""" & _clsMessageVAR.WebAdminURL & "?A=" & A & "&S=" & S & "&menu=" & menu & """ method=""POST"" style=""margin:0"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Choice"" value=""RemoveHoliday"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_Method"" value=""StoreMe"">")
                                            Response_WriteLine("<input type=""hidden"" name=""form_HoDate"" value=""" & form_HoDate & """>")
                                            Response_WriteLine("<tr bgcolor=""#d6dbe9""><th colspan=""2"">Remove a Holiday</th></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Holiday&nbsp;Date</td><td width=""100%"">" & sqlDataReader.Item("Ho_Date") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr valign=""top""><td bgcolor=""#eeeeee"" align=""right"">Holiday&nbsp;Name</td><td width=""100%"">" & sqlDataReader.Item("Ho_Name") & "</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""2"">&nbsp;</td></tr>")
                                            Response_WriteLine("<tr><td colspan=""2"">Caution: Do not remove holidays from the past<br>")
                                            Response_WriteLine("if the holiday dates are more recent than the oldest Message's Date.<br>")
                                            Response_WriteLine("The reason is that reporting for past statistics still references the holidays.<br>")
                                            If holdDate.ToString = "None Exist" Then
                                                Response_WriteLine("<font color=""orange"">No messages exist.  Is it <i>really</i> wise to remove this holiday?</font>")
                                            Else
                                                If IsDate(holdDate) Then
                                                    holdDate = CDate(holdDate)
                                                    Response_WriteLine("<br>")
                                                    Response_WriteLine("The oldest message is currently " & holdDate & ":<br>")
                                                    ' < date comparison doesn't work if holddate is of form 12/4/2012 and HoDate is of form 2012-12-4
                                                    ' if holdDate < cDate(form_HoDate) then
                                                    If DateDiff("d", holdDate, CDate(form_HoDate)) >= 0 Then
                                                        Response_WriteLine("<font color=""red"">Not safe to remove!<br>")
                                                        Response_WriteLine("Oldest message is older than the holiday date!.<br>")
                                                        Response_WriteLine("Only remove if this is an invalid holiday.</font>")
                                                    Else
                                                        Response_WriteLine("<font color=""green"">Safe to remove.<br>Oldest message is newer than the holiday date.</font>")
                                                    End If
                                                Else
                                                    Response_WriteLine("<font color=""red"">Error:<br>Oldest message's date is not of a date format.</font>")
                                                End If
                                            End If
                                            Response_WriteLine("</td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><hr color=""black""></td></tr>")
                                            Response_WriteLine("<tr><td bgcolor=""#eeeeee"" colspan=""3""><center><input type=""submit"" name=""form_Submit"" class=""btn btn-primary"" value=""Remove Holiday Now""></center></td></tr>")
                                            Response_WriteLine("</form>")
                                            Response_WriteLine("</table>")
                                            Response_WriteLine("</td></tr></table>")
                                            Response_WriteLine("</p>")
                                        End If
                                    End If

                                Catch ex As Exception
                                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                                Finally
                                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                                End Try

                                Me.ShowHolidaysTable()

                            Case Else
                                Response_WriteLine("<p>Error - Choice chosen but not Method.  Press <A HREF=""javascript:history.back()"">Back</A> and try again.</p>")
                        End Select  ' form_Choice

                    End If ' strInjection <> ""

                End If  ' form_Choice = ""

            Case "Import"
                ' provide XLSX template of what fields are required
                ' allow user to upload template
                ' show "GOOD/BAD" data verification and follow-up "import now" link
                Response_WriteLine("<p><div class=""container-fluid"">")
                Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                Response_WriteLine("<table>")
                Response_WriteLine("<tr><td>1. Save this Excel spreadsheet <a href=""MM-Import-Template.xlsx"">MM-Import-Template.xlsx</a></td></tr>")
                Response_WriteLine("<tr><td>2. Fill it out (remove the sample data)<br>")
                Response_WriteLine("&nbsp;&nbsp;&nbsp;&nbsp;a. Fill in sheets ""Teams"" and ""Admins""<br>")
                Response_WriteLine("&nbsp;&nbsp;&nbsp;&nbsp;b. Note that columns A-E will repeat multiple times for each member of each team</td></tr>")
                Response_WriteLine("<tr><td>3. Provide spreadsheet to Site Champion to have added in the Edit Setup menu</td></tr>")
                Response_WriteLine("</table>")
                Response_WriteLine("</div></div></p>")

            Case "Audit"
                ' Show Audit History for Edit Setup
                Dim auditCount

                ' AA_IP is stored but not displayed
                sSqlString = "SELECT TOP 2000 AA_Action, AA_Details, AA_Dt, AA_Tm, AA_Username FROM tab_AuditAdmin ORDER BY AA_Dt DESC, AA_Tm DESC;"

                MyCommand.CommandText = sSqlString

                Try
                    If MyConnection.State = ConnectionState.Closed Then
                        MyConnection.Open()
                    End If

                    sqlDataReader = MyCommand.ExecuteReader

                    If Not sqlDataReader.HasRows Then
                        Response_WriteLine("<p>No Audit records in history... strange... must be a brand new database.</p>")
                    Else
                        auditCount = 0
                        Response_WriteLine("<div class=""container-fluid"">")
                        Response_WriteLine("<div class=""jumbotron"" style=""border:1px solid #888; padding-left: 5px; padding-right: 5px; box-shadow:0px 2px 5px #f5f5f5;"">")
                        Response_WriteLine("<p>")
                        Response_WriteLine("<table border=""1"" cellpadding=""0"" cellspacing=""0""><tr><td>")
                        Response_WriteLine("<table class=""table table-striped table-bordered table-hover table-condensed""><tbody>")
                        Response_WriteLine("<tr bgcolor=""white""><th>Action</th><th>Details</th><th>Date</th><th>Time</th><th>Username</th></tr>")
                        While sqlDataReader.Read = True
                            If auditCount Mod 2 = 0 Then
                                Response_WriteLine("<tr valign=""top"">")
                            Else
                                Response_WriteLine("<tr valign=""top"">")
                            End If
                            Response_WriteLine("<td nowrap>" & sqlDataReader.Item("AA_Action") & "</td>")
                            Response_WriteLine("<td>" & sqlDataReader.Item("AA_Details") & "</td>")
                            Response_WriteLine("<td align=""right"" nowrap>" & sqlDataReader.Item("AA_Dt") & "</td>")
                            Response_WriteLine("<td align=""right"" nowrap>" & Me.formatTime(sqlDataReader.Item("AA_Tm"), True) & "</td>")
                            If UCase(Me.UserName) = UCase(sqlDataReader.Item("AA_Username")) Then
                                Response_WriteLine("<td nowrap><font color=red>" & Me.CleanUserName(sqlDataReader.Item("AA_Username")) & "</font></td>")
                            Else
                                Response_WriteLine("<td nowrap>" & Me.CleanUserName(sqlDataReader.Item("AA_Username")) & "</td>")
                            End If
                            Response_WriteLine("</tr>")
                            auditCount = auditCount + 1
                        End While
                        If auditCount >= 2000 Then
                            Response_WriteLine("<tr><td colspan=5><center>Only the most recent 2000 records are shown.</center></td></tr>")
                        Else
                            Response_WriteLine("<tr><td colspan=5><center>" & auditCount & " records shown.</center></td></tr>")
                        End If
                        Response_WriteLine("</tbody></table>")
                        Response_WriteLine("</td></tr></table>")
                        Response_WriteLine("</p></div></div>")
                    End If

                Catch ex As Exception
                    System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
                Finally
                    If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                    If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                    If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
                End Try

            Case Else
                Response_WriteLine("<p>Choose a Setup Menu option.</p>")
        End Select  ' Action
    End Sub

    Private Function ADarray(v As Integer) As String
        Throw New NotImplementedException()
    End Function


    '************************************************
    '
    ' Sub: Page_Load
    ' Sub is called on each page load
    '
    '************************************************
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        '
        Dim ArrayDomain(2) As String
        Dim sVISN As String
        Dim sDCPath As String
        Dim strConn As String
        Dim sqlDataReader As SqlDataReader = Nothing

        strConn = ConfigurationManager.ConnectionStrings("MMConnectionString").ToString

        Dim MyConnection = New SqlConnection(strConn)
        Dim MyCommand As New SqlCommand()
        MyCommand.Connection = MyConnection
        MyCommand.CommandType = CommandType.Text

        ' Prevent caching PII on local C drive, but allow full BACK button functionality
        ' don't use [ Response.CacheControl = "no-cache" ] because user can't hit Back to correct invalid form data, gets "Webpage has Expired" page error.
        'Response.AddHeader "Pragma", "no-cache"
        ' Response.Expires
        '	The Expires property sets how long (in minutes) a page will be cached on a browser before it expires. 
        '	If a user returns to the same page before it expires, the cached version is displayed.
        ' NOT TESTED: classic ASP of -1 sets BACK button to work as expected
        'Response.Expires = -1  
        ' TESTED: Response.Expires=0 enables Back Button w/o "webpage has expired"
        'Response.Expires = 0
        '  it to 1 minute, that's as long as a person needs to hit BACK to correct and re-submit form data
        ' anything > 0 doesn't refresh menus when person goes back to same URL within the expires time.
        'Response.Expires = 1
        ' Response.ExpiresAbsolute
        '	The ExpiresAbsolute property sets a date and time when a cached page on a browser will expire.
        '	If a user returns to the same page before this date/time, the cached version is displayed.
        'Response.ExpiresAbsolute = Now() - 1

        ' Response.CacheControl
        ' "Private" is default and indicates that only private caches may cache this page. Proxy servers will not cache pages with this setting.
        ' "Public" indicates public caches. Proxy servers will cache pages with this setting.
        Response.CacheControl = "Private"
        'Response.CacheControl="Public"
        'Response.CacheControl = "no-cache"

        Me.PageStartTime = Vb6.Timer()
        'Response.Write("Trace #1 - Beginning:<br>")
        ' ^^^ Only make variable and database pointer changes to MessageVAR.asp
        ' Nothing in this file needs to be tweaked per site.
        '
        ' SAME SAME SAME
        ' Message.asp exists in user level and in MessageAdmin folder
        ' SAME SAME SAME
        '
        ' THESE FILES EXIST:
        ' \Message\Message.asp
        ' \Message\MessageVAR.asp
        ' \Message\MessageAdmin\Message.asp
        ' \Message\MessageAdmin\MessageVAR.asp
        ' \Message\MessageAdmin\Message90210.mdb
        '
        ' THESE IIS 2003 SETTINGS:
        ' \Message\   <--- this folder (and subfolders) have Windows Authentication enabled, Anonymous Disabled
        ' \Message\MessageAdmin   <--- this folder has IUSR=Read/WRite (so MDB temp files can be created by IIS service account)
        ' \Message\MessageAdmin\Message90210.mdb   <--- this file has Read unchecked in IIS console (so somebody can't download it by name)
        '
        ' IIS 2007 SETTINGS, see Setup SOP.
        '
        ' DATABASE SETTINGS:
        ' The Purge menu requires Relationship with Delete Cascade between 1 (tab_Messages) and Many (tab_Audit)
        ' tab.Messages.Msg_Index --- > tab_Audit.Au_IndexMessage
        ' In Access, choose Database Tools tab and click the Relationships button:
        ' 1. Add tab_Messages and Audit tables
        ' 2. Drag line between tab_Messages.Msg_Index and tab_Audit.Au_IndexMessage
        ' 3. Check = Enforce Referential Integrety
        ' 4. Uncheck = Case Update Related Fields
        ' 5. Check = Cascade Delete Related Records
        ' 6. Relationship Type: One-To-Many
        ' 7. Click the Create button
        ' 8. Click SAVE and close   (takes half a minute to save)
        '
        ' ==============================================================================================
        ' start of global definitions
        '===========================================================
        MyCommand.CommandText = "SELECT * FROM tab_Globals;"

        Try
            If MyConnection.State = ConnectionState.Closed Then
                MyConnection.Open()
            End If

            sqlDataReader = MyCommand.ExecuteReader

            If Not sqlDataReader.HasRows Then
                System.Web.HttpContext.Current.Session(“Oops”) = "*** No record found in global table - tab_Globals ***"
            Else
                sqlDataReader.Read()

                ' the From address for outgoing emails
                _clsMessageVAR.AdminEmailAddress = sqlDataReader.Item("Gl_adminEmailAddress")

                _clsMessageVAR.WebURL = sqlDataReader.Item("Gl_webURL")
                '_clsMessageVAR.WebURL = "http://localhost:16682/message.aspx"
                System.Web.HttpContext.Current.Session(“webURL”) = _clsMessageVAR.WebURL

                _clsMessageVAR.WebAdminURL = sqlDataReader.Item("Gl_webAdminURL")
                '_clsMessageVAR.WebAdminURL = "http://localhost:16682/message.aspx"
                System.Web.HttpContext.Current.Session(“WebAdminURL”) = _clsMessageVAR.WebAdminURL

                ' the site Name
                ArrayDomain = Split(Page.User.Identity.Name, "\")

                Select Case UCase(ArrayDomain(0))
                    Case "VHA01"
                        sVISN = "VISN 01"
                        sDCPath = "DC=v01,DC=med,DC=va,DC=gov"
                    Case "VHA02"
                        sVISN = "VISN 02"
                        sDCPath = "DC=v02,DC=med,DC=va,DC=gov"
                    Case "VHA03"
                        sVISN = "VISN 03"
                        sDCPath = "DC=v03,DC=med,DC=va,DC=gov"
                    Case "VHA04"
                        sVISN = "VISN 04"
                        sDCPath = "DC=v04,DC=med,DC=va,DC=gov"
                    Case "VHA05"
                        sVISN = "VISN 05"
                        sDCPath = "DC=v05,DC=med,DC=va,DC=gov"
                    Case "VHA06"
                        sVISN = "VISN 06"
                        sDCPath = "DC=v06,DC=med,DC=va,DC=gov"
                    Case "VHA07"
                        sVISN = "VISN 07"
                        sDCPath = "DC=v07,DC=med,DC=va,DC=gov"
                    Case "VHA08"
                        sVISN = "VISN 08"
                        sDCPath = "DC=v08,DC=med,DC=va,DC=gov"
                    Case "VHA09"
                        sVISN = "VISN 09"
                        sDCPath = "DC=v09,DC=med,DC=va,DC=gov"
                    Case "VHA10"
                        sVISN = "VISN 10"
                        sDCPath = "DC=v10,DC=med,DC=va,DC=gov"
                    Case "VHA11"
                        sVISN = "VISN 11"
                        sDCPath = "DC=v11,DC=med,DC=va,DC=gov"
                    Case "VHA12"
                        sVISN = "VISN 12"
                        sDCPath = "DC=v12,DC=med,DC=va,DC=gov"
                    Case "VHA13"
                        sVISN = "VISN 13"
                        sDCPath = "DC=v13,DC=med,DC=va,DC=gov"
                    Case "VHA14"
                        sVISN = "VISN 14"
                        sDCPath = "DC=v14,DC=med,DC=va,DC=gov"
                    Case "VHA15"
                        sVISN = "VISN 15"
                        sDCPath = "DC=v15,DC=med,DC=va,DC=gov"
                    Case "VHA16"
                        sVISN = "VISN 16"
                        sDCPath = "DC=v16,DC=med,DC=va,DC=gov"
                    Case "VHA17"
                        sVISN = "VISN 17"
                        sDCPath = "DC=v17,DC=med,DC=va,DC=gov"
                    Case "VHA18"
                        sVISN = "VISN 18"
                        sDCPath = "DC=v18,DC=med,DC=va,DC=gov"
                    Case "VHA19"
                        sVISN = "VISN 19"
                        sDCPath = "DC=v19,DC=med,DC=va,DC=gov"
                    Case "VHA20"
                        sVISN = "VISN 20"
                        sDCPath = "DC=v20,DC=med,DC=va,DC=gov"
                    Case "VHA21"
                        sVISN = "VISN 21"
                        sDCPath = "DC=v21,DC=med,DC=va,DC=gov"
                    Case "VHA22"
                        sVISN = "VISN 22"
                        sDCPath = "DC=v22,DC=med,DC=va,DC=gov"
                    Case "VHA23"
                        sVISN = "VISN 23"
                        sDCPath = "DC=v23,DC=med,DC=va,DC=gov"
                    Case "R01"
                        sVISN = "Region 01"
                        sDCPath = "DC=r01,DC=med,DC=va,DC=gov"
                    Case "R02"
                        sVISN = "Region 02"
                        sDCPath = "DC=r02,DC=med,DC=va,DC=gov"
                    Case "R03"
                        sVISN = "Region 03"
                        sDCPath = "DC=r03,DC=med,DC=va,DC=gov"
                    Case "R04"
                        sVISN = "Region 04"
                        sDCPath = "DC=r04,DC=med,DC=va,DC=gov"
                    Case "VHAMASTER"
                        sVISN = "Master"
                        sDCPath = "DC=vha,DC=med,DC=va,DC=gov"
                    Case "VHA"
                        sVISN = "VHA"
                        sDCPath = "DC=vha,DC=med,DC=va,DC=gov"
                    Case "VA"
                        sVISN = "VA"
                        sDCPath = "DC=va,DC=gov"
                    Case "VBA"
                        sVISN = "VBA"
                        sDCPath = "DC=vba,DC=med,DC=va,DC=gov"
                    Case Else
                        sVISN = "VISN"
                        sDCPath = "DC=med,DC=va,DC=gov"
                End Select

                _clsMessageVAR.UserVISN = sVISN
                _clsMessageVAR.DCPath = sDCPath
                ' go back to consolidated single site (not based on user login)
                _clsMessageVAR.WebName = sqlDataReader.Item("Gl_webName")

                ' Yes=sends to tab_Members.Me_Email or tab_Admins.Adm_Email value, No=sends to adminEmailAddress
                _clsMessageVAR.EmailActive = sqlDataReader.Item("Gl_emailActive")

                ' the SMTP server DNS
                _clsMessageVAR.EmailServer = sqlDataReader.Item("Gl_emailServer")

                ' Global field overrides
                _clsMessageVAR.Gl_overrideLName = sqlDataReader.Item("Gl_overrideLName") ' Patient Last Name
                _clsMessageVAR.Gl_overrideFName = sqlDataReader.Item("Gl_overrideFName") ' Patient First Name
                _clsMessageVAR.Gl_overrideL4 = sqlDataReader.Item("Gl_overrideL4") ' Patient Last 4 SSN
                _clsMessageVAR.Gl_overridePhone = sqlDataReader.Item("Gl_overridePhone") ' Patient Phone
                _clsMessageVAR.Gl_overrideRCall = sqlDataReader.Item("Gl_overrideRCall") ' Return Call
                _clsMessageVAR.Gl_overrideReason = sqlDataReader.Item("Gl_overrideReason") ' Reason
                _clsMessageVAR.Gl_overrideComment = sqlDataReader.Item("Gl_overrideComment") ' Comment
                _clsMessageVAR.Gl_overrideDOB = sqlDataReader.Item("Gl_overrideDOB") ' Date of Birth
                _clsMessageVAR.Gl_overrideTeamColorize = sqlDataReader.Item("Gl_overrideTeamColorize") ' Team color (display color as BG vs. font)
            End If

        Catch ex As Exception
            System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
        Finally
            If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
            If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
            If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
        End Try

        ' correct to "Message.aspx" if other cases are typed into Globals table
        _clsMessageVAR.WebURL = Replace(_clsMessageVAR.WebURL, "message.aspx", "message.aspx")
        _clsMessageVAR.WebURL = Replace(_clsMessageVAR.WebURL, "MESSAGE.ASPX", "message.aspx")
        Me.Whatsite = Request.Form("form_SiteNum")
        Me.Whatlocation = Request.Form("form_LocationIndex")
        UserIP = Request.ServerVariables("REMOTE_ADDR")
        If Me.UserIP = "" Then
            ' couln't get from server variables,  to "None" for sSqlString insert.
            Me.UserIP = "None"
        Else
            ' OK
        End If
        UserName = Request.ServerVariables("REMOTE_USER")
        If Me.UserName = "" Then
            ' couln't get from server variables,  to "None" for sSqlString insert.
            Me.UserName = "None"
        Else
            ' OK
            'in form of: UserName = "VHA12\VHAMADSmithC"
        End If
        'If UserName = "VHA23\VHAMINDempsT" Then UserName = "VHA12\VHAMADBERGM"
        'If UserName = "VHA23\VHAMINDempsT0" Then UserName = "VHA23\VHAMINKIRBYS"
        'If UserName = "VHA23\VHAMINDempsT0" Then UserName = "VHA12\VHAMADPROVEJ"
        'If UserName = "VHA23\VHAMINDempsT0" Then UserName = "VHA23\VHAMINDempsT"
        'bDebug = true
        'UserName = "VHA12\VHAHINHertzB" ' member of multiple teams
        'UserName = "VHA12\VHAHINCunniC" ' member of 6 teams
        'UserName = "VHA12\VHAHINBurrR" ' member of single team
        'UserName = "VHA12\VHAMADHillL" ' madison member of multiple teams
        'webURL = "https://phonetest.madison.med.va.gov/message/test4/Message.asp"
        'webAdminURL = "https://phonetest.madison.med.va.gov/message/test4/messageadmin/Message.asp"

        ' SiteNum, Index, Admin Menu item
        If (Not Request.QueryString("S") Is Nothing) Then
            S = Me.JustToTheFirstSpace(Me.killChars(Request.QueryString("S").ToString()))
        Else
            S = ""
        End If

        If (Not Request.QueryString("I") Is Nothing) Then
            I = Me.JustToTheFirstSpace(Me.killChars(Request.QueryString("I").ToString()))
        Else
            I = ""
        End If

        If (Not Request.QueryString("A") Is Nothing) Then
            A = Me.JustToTheFirstSpace(Me.killChars(Request.QueryString("A").ToString()))
        Else
            A = ""
        End If

        If (Not Request.QueryString("L") Is Nothing) Then
            L = Me.JustToTheFirstSpace(Me.killChars(Request.QueryString("L").ToString())) ' used for Location entry
        Else
            L = ""
        End If

        ' global values that are filled in when calling sub ParseFullID(fullID)
        Me.GLAST = ""
        Me.GFIRST = ""
        Me.GSSN = ""

        If Me.Whatsite <> "" Then
            MyCommand.CommandText = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & Me.Whatsite & "' AND tab_Sites.Si_Active = 'Yes';"
        Else
            If S <> "" Then
                MyCommand.CommandText = "SELECT * FROM tab_Sites WHERE tab_Sites.Si_SiteNum = '" & S & "' AND tab_Sites.Si_Active = 'Yes';"
            Else
                MyCommand.CommandText = ""
            End If
        End If
        If MyCommand.CommandText <> "" Then
            Try
                If MyConnection.State = ConnectionState.Closed Then
                    MyConnection.Open()
                End If

                sqlDataReader = MyCommand.ExecuteReader

                If Not sqlDataReader.HasRows Then
                    ' admin menu, no site chosen
                    Me.SiteName = ""
                Else
                    sqlDataReader.Read()

                    If IsDBNull(sqlDataReader.Item("Si_Name")) Then
                        Me.SiteName = ""
                    Else
                        Me.SiteName = sqlDataReader.Item("Si_Name")
                    End If
                End If

            Catch ex As Exception
                System.Web.HttpContext.Current.Session(“Oops”) = ex.Message
            Finally
                If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
                If (Not sqlDataReader Is Nothing) Then sqlDataReader.Close()
                If System.Web.HttpContext.Current.Session(“Oops”) <> "" Then Server.Transfer("oops.aspx")
            End Try
        Else
            ' OK to be here, nothing chosen
            Me.SiteName = ""
        End If
        ' AdminAccess = String = explaining the level of access
        '   ="Admin" for "000" or "SiteNum"
        '   ="Site" for "000" or "SiteNum" (or listed multiple times for multiple sites)
        '   ="Member"
        '   ="None" (for all other people that just come here to submit new messages)
        Me.AdminAccess = "None"
        ' AdminSite = String = the Site code has access to:
        '   "None" = initialized 
        '   ="000" for all (multiple sites)
        '   ="xxx" tab_Sites.Si_SiteNum = tab_Locations.Lo_SiteNum (if it's a member)
        Me.AdminSite = "None"
        ' AdminLocation = Number = the Location has access to:
        '   0 = initialized
        '   =tab_Locations.Lo_Index=tab_Teams.Te_LocationIndex (if it's a member)
        '   =-1 (if member's Teams span multiple Locations)
        Me.AdminLocation = 0
        ' AdminTeam = Number = the Team has access to:
        '   0 = initialized
        '   =tab_Teams.Te_Index (if member with 1 Team)
        '   =-1 (if member has multiple Teams)
        Me.AdminTeam = 0
        ' AdminType = String = the Type has access to:
        '	"None" = initialized
        '	if in Admins table, reference tab_Admins.Adm_Type:
        '		= {All, PACT, FEE, ... etc}
        '	else if in Members table:
        '		= value of last tab_Locations.Lo_Type
        Me.AdminType = "None"
        ' Prediction order: 2 / 3
        If A = "Setup" Or A = "Admin" Then
            ' CheckAdmin() checks accses levels, fills in the Adminxxxxx variables, loads UserSID from AD
            ' skip overhead of checking for access levels if not in the A="Setup" or A="Admin" menu items
            Me.CheckAdmin()
        End If
        If S = "" And Me.AdminSite <> "000" And Me.AdminSite <> "None" Then
            ' when an Admin is assigned 1 SiteNum,  S to be that.  Won't  for global admins
            S = Me.AdminSite
        End If
        ' end of global definitions
        ' ==============================================================================================
        'Sub SleepOLD(intSeconds)
        '	' this  Me.Sleep( functions sucks up 100% of 1 CPU core... ) 
        '	dim dteStart, dteEnd
        '	
        '	dteStart = Time()
        '	dteEnd = DateAdd("s", intSeconds, dteStart)
        '
        '	While dteEnd > Time()
        '		DoNothing()
        '	End While
        'End Sub
        ' 
        'Sub DoNothing
        '	'While/Wend has quirks when it is Nothing
        ' ------------------------------------------------------------------------
        ' ------------------------------------------------------------------------
        ' ------------------------------------------------------------------------
        ' ------------------------------------------------------------------------
        Me.ShowHTMLHeader()
        If _clsMessageVAR.BDebug Then Me.Debug("All")
        If (Not Request.QueryString("menu") Is Nothing) Then
            If Request.QueryString("menu").ToString() = "Help" Then
                ' A=Admin or A=Setup can show menu="Help" to allow AdminAccess variables to be
                bShowHelpMenu = True
                Me.ShowHelp()
            End If
        End If
        If Not bShowHelpMenu Then
            Select Case A
                Case "Setup"
                    If Me.AdminAccess = "Admin" Then
                        Me.ShowSetupMenu()
                    Else
                        ' not allowed for {"Site", "None"} (None = Member level)
                        Response_WriteLine("<p><font color=red>No Setup Menu access allowed for " & Me.UserName & ".</font></p>")
                    End If

                Case "Admin"
                    ' Admin Menu - S has a value: 0, 607, 595, etc
                    If Me.AdminAccess <> "None" Then
                        ' ADMIN Menu for {"Admin", "Site", "Member"}
                        Me.ShowAdminMenu()
                    Else
                        Response_WriteLine("<p><font color=red>No Menu access allowed for " & Me.UserName & ".</font></p>")
                    End If

                Case "Help"
                    Me.ShowHelp()

                Case Else
                    ' not the admin menu, so do a new form
                    Me.ShowMainMenu()
            End Select
        End If
        If _clsMessageVAR.BDebug Then Me.Debug("All")
        Me.ShowHTMLFooter()
        ' ------------------------------------------------------------------------
        ' ------------------------------------------------------------------------
        ' ------------------------------------------------------------------------
        ' ------------------------------------------------------------------------
    End Sub

    Public Sub Redirect(ByVal url As String, Optional ByVal hasErrored As Boolean = False)
        If Not hasErrored Then
            HttpContext.Current.Response.Redirect(url, True)
            HttpContext.Current.ApplicationInstance.CompleteRequest()
        Else
            HttpContext.Current.Server.ClearError()
            HttpContext.Current.Response.Redirect(url, True)
            HttpContext.Current.ApplicationInstance.CompleteRequest()
        End If
    End Sub

    Protected Overrides Sub Finalize()
    End Sub

End Class
