<%
'=============================================================================
' FILE: displayprinter.asp
' PURPOSE: Display detailed printer information with edit capability
' SECURITY: Parameterized queries, HTML encoding, input validation
' UPDATED: 2025-10-27 - Migrated to secure patterns
'=============================================================================
%><!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
  <!--#include file="./includes/validation.asp"-->
  <!--#include file="./includes/db_helpers.asp"-->
  <!--#include file="./includes/data_cache.asp"-->
  <!--#include file="./includes/zabbix_all_supplies_cached.asp"-->
</head>

<%
	theme = Request.Cookies("theme")
	IF theme = "" THEN
		theme="bg-theme1"
	END IF

	'=============================================================================
	' SECURITY: Validate printerid parameter
	'=============================================================================
	Dim printerid
	printerid = GetSafeInteger("QS", "printerid", 0, 1, 999999)

	IF printerid = 0 THEN
		objConn.Close
		Response.Redirect("default.asp")
		Response.End
	END IF

	'=============================================================================
	' SECURITY: Use parameterized query to prevent SQL injection
	' NOTE: Explicitly select printers.maptop and printers.mapleft (not from machines)
	'=============================================================================
	strSQL =	"SELECT machines.*, models.*, vendors.*, printers.*, " &_
			"printers.maptop AS printer_maptop, printers.mapleft AS printer_mapleft " &_
			"FROM machines,models,vendors,printers WHERE " &_
			"printers.machineid=machines.machineid AND "&_
			"printers.modelid=models.modelnumberid AND "&_
			"models.vendorid=vendors.vendorid AND "&_
			"printers.printerid=?"
	set rs = ExecuteParameterizedQuery(objConn, strSQL, Array(printerid))

	' Check if printer exists
	If rs.EOF Then
		rs.Close
		Set rs = Nothing
		objConn.Close
		Response.Redirect("default.asp")
		Response.End
	End If

	Dim machineid
	machineid	=	rs("machineid")
%>

<body class="bg-theme <%=Server.HTMLEncode(theme)%>">

<!-- start loader -->
   <div id="pageloader-overlay" class="visible incoming"><div class="loader-wrapper-outer"><div class="loader-wrapper-inner" ><div class="loader"></div></div></div></div>
   <!-- end loader -->
<!-- Start wrapper-->
 <div id="wrapper">
  <!--#include file="./includes/leftsidebar.asp"-->
<!--Start topbar header-->
  <!--#include file="./includes/topbarheader.asp"-->
<!--End topbar header-->
<div class="clearfix"></div>

  <div class="content-wrapper">
    <div class="container-fluid">

      <div class="row mt-3">
        <div class="col-lg-4">
           <div class="card profile-card-2">
            <div class="card-img-block">
               		 <img class="img-fluid" src="./images/printers/<%=Server.HTMLEncode(rs("image") & "")%>" alt="Card image cap">
            </div>
            <div class="card-body pt-5">
                <img src="./images/printers/<%=Server.HTMLEncode(rs("image") & "")%>" alt="profile-image" class="profile">
                <h5 class="card-title"><%=Server.HTMLEncode(rs("vendor") & "")%></h5>
                <p class="card-text"><a href="<%=Server.HTMLEncode(rs("documentationpath") & "")%>" title="Click to Access Support Docs" target="_blank"><%=Server.HTMLEncode(rs("modelnumber") & "")%></a></p>
            </div>
        </div>
        </div>
        <div class="col-lg-8">
           <div class="card">
            <div class="card-body">
            <ul class="nav nav-tabs nav-tabs-primary top-icon nav-justified">
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#profile" data-toggle="pill" class="nav-link active"><i class="icon-wrench"></i> <span class="hidden-xs">Settings</span></a>
                </li>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#edit" data-toggle="pill" class="nav-link"><i class="icon-note"></i> <span class="hidden-xs">Edit</span></a>
                </li>
            </ul>
            <div class="tab-content p-3">
                <div class="tab-pane active" id="profile">
                    <h5 class="mb-3">Configuration</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <p class="mb-2"><strong>Vendor:</strong></p>
                            <p class="mb-2"><strong>Model:</strong></p>
                            <p class="mb-2"><strong>Serial:</strong></p>
                            <p class="mb-2"><strong>Location:</strong></p>
                            <p class="mb-2"><strong>IP:</strong></p>
                            <p class="mb-2"><strong>FQDN:</strong></p>
                            <p class="mb-2"><strong>PIN:</strong></p>
                            <p class="mb-2"><strong>Driver:</strong></p>
                            <p class="mb-2"><strong>CSF Name:</strong></p>
                            <p class="mb-2"><strong>Windows Name:</strong></p>
                        </div>
                        <div class="col-md-7">
<%
			Dim vendorVal, modelVal, serialVal, machineVal, ipVal, fqdnVal, pinVal, csfVal, winNameVal

			' Get values and default to N/A if empty
			vendorVal = rs("vendor") & ""
			If vendorVal = "" Then vendorVal = "N/A"

			modelVal = rs("modelnumber") & ""
			If modelVal = "" Then modelVal = "N/A"

			serialVal = rs("serialnumber") & ""
			If serialVal = "" Then serialVal = "N/A"

			machineVal = rs("machinenumber") & ""
			If machineVal = "" Then machineVal = "N/A"

			ipVal = rs("ipaddress") & ""
			If ipVal = "" Then ipVal = "N/A"

			fqdnVal = rs("fqdn") & ""
			If fqdnVal = "" Then fqdnVal = "N/A"

			pinVal = rs("printerpin") & ""
			If pinVal = "" Then pinVal = "N/A"

			csfVal = rs("printercsfname") & ""
			If csfVal = "" Then csfVal = "N/A"

			winNameVal = rs("printerwindowsname") & ""
			If winNameVal = "" Then winNameVal = "N/A"
%>
                            <p class="mb-2"><%=Server.HTMLEncode(vendorVal)%></p>
                            <p class="mb-2">
<%
			If modelVal <> "N/A" And rs("documentationpath") & "" <> "" Then
				Response.Write("<a href='" & Server.HTMLEncode(rs("documentationpath") & "") & "' title='Click to Access Support Docs' target='_blank'>" & Server.HTMLEncode(modelVal) & "</a>")
			Else
				Response.Write(Server.HTMLEncode(modelVal))
			End If
%>
                            </p>
                            <p class="mb-2"><%=Server.HTMLEncode(serialVal)%></p>
                            <p class="mb-2">
<%
			If machineVal <> "N/A" Then
%>
                                <span class="location-link" data-printerid="<%=Server.HTMLEncode(printerid)%>" style="cursor:pointer; color:#007bff;">
                                    <i class="zmdi zmdi-pin" style="margin-right:4px;"></i><%=Server.HTMLEncode(machineVal)%>
                                </span>
<%
			Else
				Response.Write("N/A")
			End If
%>
                            </p>
                            <p class="mb-2">
<%
			If ipVal <> "N/A" Then
				Response.Write("<a href='http://" & Server.HTMLEncode(ipVal) & "' title='Click to Access Printer Admin Page' target='_blank'>" & Server.HTMLEncode(ipVal) & "</a>")
			Else
				Response.Write("N/A")
			End If
%>
                            </p>
                            <p class="mb-2"><%=Server.HTMLEncode(fqdnVal)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(pinVal)%></p>
                            <p class="mb-2">
<%
			' Driver download - use icon link to maintain alignment
			IF rs("installpath") & "" <> "" THEN
				response.write ("<a href='./" & Server.HTMLEncode(rs("installpath") & "") & "' title='Download Specific Installer'><i class='zmdi zmdi-download' style='font-size:1.2rem; color:#007bff;'></i> <span style='color:#007bff;'>Specific Installer</span></a>")
			ELSE
				response.write ("<a href='./install_printer.asp?printerid=" & Server.HTMLEncode(printerid) & "' title='Download Universal Driver Installer'><i class='zmdi zmdi-download' style='font-size:1.2rem; color:#28a745;'></i> <span style='color:#28a745;'>Universal Installer</span></a>")
			END IF
%>
                            </p>
                            <p class="mb-2"><%=Server.HTMLEncode(csfVal)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(winNameVal)%></p>
                        </div>
                        <div class="col-md-12">
<%
' Get Zabbix data for this printer (cached) - now includes all supplies
Dim printerIP, cachedData, zabbixConnected, pingStatus, suppliesJSON
Dim statusBadge, statusIcon, statusColor

printerIP = rs("ipaddress")

' Get all supplies data (toner, ink, drums, maintenance kits, etc.)
' Returns array: [zabbixConnected, pingStatus, suppliesJSON]
cachedData = GetAllPrinterSuppliesCached(printerIP)

' Extract data from array
zabbixConnected = cachedData(0)
pingStatus = cachedData(1)
suppliesJSON = cachedData(2)
%>
                            <h5 class="mt-2 mb-3">
                                Supply Status
<%
' Display printer online/offline status badge
If pingStatus = "1" Then
    Response.Write(" <span class='badge badge-success'><i class='zmdi zmdi-check-circle'></i> Online</span>")
ElseIf pingStatus = "0" Then
    Response.Write(" <span class='badge badge-danger'><i class='zmdi zmdi-alert-circle'></i> Offline</span>")
Else
    Response.Write(" <span class='badge badge-secondary'><i class='zmdi zmdi-help'></i> Unknown</span>")
End If
%>
                            </h5>
                             <div class="table-responsive">
<%
If zabbixConnected <> "1" Then
    ' Show error details
    If zabbixConnected = "" Then
        Response.Write("<div class='alert alert-warning'><i class='zmdi zmdi-alert-triangle'></i> Unable to connect to Zabbix monitoring server (empty response)</div>")
    Else
        Response.Write("<div class='alert alert-danger'><strong>Zabbix Connection Error:</strong><br><pre style='white-space: pre-wrap;'>" & Server.HTMLEncode(zabbixConnected) & "</pre></div>")
    End If
ElseIf suppliesJSON = "" Or IsNull(suppliesJSON) Then
    Response.Write("<div class='alert alert-info'><i class='zmdi zmdi-info'></i> No supply data available for this printer in Zabbix (IP: " & printerIP & ")</div>")
Else
    ' Parse the JSON data for all supply items
    Dim itemStart, itemEnd, itemBlock, itemName, itemValue
    Dim namePos, nameStart, nameEnd, valuePos, valueStart, valueEnd
    Dim currentPos, hasData

    hasData = False

    ' Find all items with "Level" in the name (toner, ink, drums, maintenance kits, etc.)
    currentPos = 1
    Do While currentPos > 0
        itemStart = InStr(currentPos, suppliesJSON, "{""itemid""")
        If itemStart = 0 Then Exit Do

        itemEnd = InStr(itemStart + 1, suppliesJSON, "},")
        If itemEnd = 0 Then
            itemEnd = InStr(itemStart + 1, suppliesJSON, "}]")
        End If
        If itemEnd = 0 Then Exit Do

        itemBlock = Mid(suppliesJSON, itemStart, itemEnd - itemStart + 1)

        ' Extract name
        namePos = InStr(itemBlock, """name"":""")
        If namePos > 0 Then
            nameStart = namePos + 8
            nameEnd = InStr(nameStart, itemBlock, """")
            itemName = Mid(itemBlock, nameStart, nameEnd - nameStart)
        Else
            itemName = ""
        End If

        ' Only process items with "Level" in the name
        If InStr(1, itemName, "Level", 1) > 0 Then
            ' Extract value (lastvalue)
            valuePos = InStr(itemBlock, """lastvalue"":""")
            If valuePos > 0 Then
                valueStart = valuePos + 13
                valueEnd = InStr(valueStart, itemBlock, """")
                itemValue = Mid(itemBlock, valueStart, valueEnd - valueStart)

                ' Try to convert to numeric
                On Error Resume Next
                Dim numericValue, progressClass
                numericValue = CDbl(itemValue)
                If Err.Number = 0 Then
                    ' Determine progress bar color based on level
                    If numericValue < 10 Then
                        progressClass = "bg-danger"      ' Red for critical (< 10%)
                    ElseIf numericValue < 25 Then
                        progressClass = "bg-warning"     ' Yellow for low (< 25%)
                    Else
                        progressClass = "bg-success"     ' Green for good (>= 25%)
                    End If

                    ' Display supply level with progress bar
                    Response.Write("<div class='mb-3'>")
                    Response.Write("<div class='d-flex justify-content-between mb-1'>")
                    Response.Write("<span><strong>" & Server.HTMLEncode(itemName) & "</strong></span>")
                    Response.Write("<span>" & Round(numericValue, 1) & "%</span>")
                    Response.Write("</div>")
                    Response.Write("<div class='progress' style='height: 25px;'>")
                    Response.Write("<div class='progress-bar " & progressClass & "' role='progressbar' style='width: " & numericValue & "%;' aria-valuenow='" & numericValue & "' aria-valuemin='0' aria-valuemax='100'>" & Round(numericValue, 1) & "%</div>")
                    Response.Write("</div>")
                    Response.Write("</div>")

                    hasData = True
                End If
                Err.Clear
                On Error Goto 0
            End If
        End If

        currentPos = itemEnd + 1
    Loop

    If Not hasData Then
        Response.Write("<div class='alert alert-info'><i class='zmdi zmdi-info'></i> No supply level data available for this printer in Zabbix (IP: " & printerIP & ")</div>")
    End If
End If
%>
                          </div>
                        </div>
                    </div>
                    <!--/row-->
                </div>
                <div class="tab-pane" id="edit">
  			<form method="post" action="./editprinter.asp?printerid=<%=Server.HTMLEncode(printerid)%>">
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Vendor:</label>
                            <div class="col-lg-9">
                                <select name="vendorid" class="form-control">
                                    <option value='<%=Server.HTMLEncode(rs("vendorid") & "")%>'><%=Server.HTMLEncode(rs("vendor") & "")%></option>
<%
			' Use cached vendor data instead of database query
			Response.Write(RenderVendorOptions(rs("vendorid")))
%>
                                </select>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Model</label>
                            <div class="col-lg-9">
                                <div class="input-group">
                                    <select name="modelid" id="modelid" class="form-control">
                                        <option value='<%=Server.HTMLEncode(rs("modelnumberid") & "")%>'><%=Server.HTMLEncode(rs("modelnumber") & "")%></option>
<%
			' Use cached model data instead of database query
			Response.Write(RenderModelOptions(rs("modelnumberid")))
%>
                                        <option value="new">+ Add New Model</option>
                                    </select>
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-info" id="addModelBtn">
                                            <i class="zmdi zmdi-plus"></i> New
                                        </button>
                                    </div>
                                </div>

                                <!-- Hidden section for adding new model -->
                                <div id="newModelSection" style="display:none; padding:15px; background:rgba(255,255,255,0.08); border:1px solid rgba(255,255,255,0.15); border-radius:5px; margin-top:10px;">
                                    <h6 class="mb-3"><i class="zmdi zmdi-plus-circle"></i> New Printer Model</h6>

                                    <div class="form-group">
                                        <label for="newmodelnumber">Model Number <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="newmodelnumber" name="newmodelnumber"
                                               maxlength="255" placeholder="e.g., LaserJet Pro 400">
                                    </div>

                                    <div class="form-group">
                                        <label for="newvendorid">Vendor <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <select class="form-control" id="newvendorid" name="newvendorid">
                                                <option value="">-- Select Vendor --</option>
<%
    Dim rsVendorsEdit
    strSQL = "SELECT vendorid, vendor FROM vendors WHERE isprinter = 1 AND isactive = 1 ORDER BY vendor ASC"
    Set rsVendorsEdit = objConn.Execute(strSQL)
    While Not rsVendorsEdit.EOF
        Response.Write("<option value='" & rsVendorsEdit("vendorid") & "'>" & Server.HTMLEncode(rsVendorsEdit("vendor")) & "</option>")
        rsVendorsEdit.MoveNext
    Wend
    rsVendorsEdit.Close
    Set rsVendorsEdit = Nothing
%>
                                                <option value="new">+ Add New Vendor</option>
                                            </select>
                                            <div class="input-group-append">
                                                <button type="button" class="btn btn-info" id="addVendorBtn">
                                                    <i class="zmdi zmdi-plus"></i> New
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Hidden section for adding new vendor -->
                                    <div id="newVendorSection" style="display:none; padding:15px; background:rgba(255,255,255,0.08); border:1px solid rgba(255,255,255,0.15); border-radius:5px; margin-bottom:15px;">
                                        <h6 class="mb-3"><i class="zmdi zmdi-plus-circle"></i> New Vendor</h6>

                                        <div class="form-group">
                                            <label for="newvendorname">Vendor Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="newvendorname" name="newvendorname"
                                                   maxlength="50" placeholder="e.g., HP, Canon, Epson">
                                        </div>

                                        <button type="button" class="btn btn-sm btn-secondary" id="cancelNewVendor">
                                            <i class="zmdi zmdi-close"></i> Cancel
                                        </button>
                                    </div>

                                    <div class="form-group">
                                        <label for="newmodelnotes">Model Notes</label>
                                        <textarea class="form-control" id="newmodelnotes" name="newmodelnotes"
                                                  rows="2" maxlength="255"
                                                  placeholder="Additional notes about this model..."></textarea>
                                    </div>

                                    <div class="form-group">
                                        <label for="newmodeldocpath">Documentation Path</label>
                                        <input type="text" class="form-control" id="newmodeldocpath" name="newmodeldocpath"
                                               maxlength="255" placeholder="\\server\docs\printer.pdf or http://...">
                                    </div>

                                    <button type="button" class="btn btn-sm btn-secondary" id="cancelNewModel">
                                        <i class="zmdi zmdi-close"></i> Cancel
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Serial:</label>
                            <div class="col-lg-9">
                                <input class="form-control" type="text" name="serialnumber" value="<%=Server.HTMLEncode(rs("serialnumber") & "")%>" placeholder="<%=Server.HTMLEncode(rs("serialnumber") & "")%>">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">IP:</label>
                            <div class="col-lg-9">
                                <input class="form-control" type="text" name="ipaddress" value="<%=Server.HTMLEncode(rs("ipaddress") & "")%>" placeholder="<%=Server.HTMLEncode(rs("serialnumber") & "")%>">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">FQDN:</label>
                            <div class="col-lg-9">
                                <input class="form-control" type="text" name="fqdn" value="<%=Server.HTMLEncode(rs("fqdn") & "")%>" placeholder="<%=Server.HTMLEncode(rs("fqdn") & "")%>">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">CSF Name:</label>
                            <div class="col-lg-9">
                                <input class="form-control" type="text" name="printercsfname" value="<%=Server.HTMLEncode(rs("printercsfname") & "")%>" placeholder="<%=Server.HTMLEncode(rs("printercsfname") & "")%>">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Windows Name::</label>
                            <div class="col-lg-9">
                                <input class="form-control" type="text" name="printerwindowsname" value="<%=Server.HTMLEncode(rs("printerwindowsname") & "")%>" placeholder="<%=Server.HTMLEncode(rs("printerwindowsname") & "")%>">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Location (Machine):</label>
                            <div class="col-lg-9">
                                <select name="machineid" class="form-control">
                                    <option value='<%=Server.HTMLEncode(rs("machineid") & "")%>'><%=Server.HTMLEncode(rs("machinenumber") & "")%></option>
<%
			' SECURITY: Query is safe (no user input), HTML encode output
			' Get all machines for dropdown
			Dim rsMachines, sqlMachines
			sqlMachines = "SELECT machineid, machinenumber, alias FROM machines WHERE isactive=1 ORDER BY machinenumber ASC"
			Set rsMachines = objconn.Execute(sqlMachines)
			While Not rsMachines.EOF
				If CLng(rsMachines("machineid")) <> CLng(rs("machineid")) Then
					Dim displayName
					If NOT IsNull(rsMachines("alias")) AND rsMachines("alias") <> "" Then
						displayName = rsMachines("machinenumber") & " (" & rsMachines("alias") & ")"
					Else
						displayName = rsMachines("machinenumber")
					End If
					Response.Write("<option value='" & Server.HTMLEncode(rsMachines("machineid") & "") & "'>" & Server.HTMLEncode(displayName & "") & "</option>")
				End If
				rsMachines.MoveNext
			Wend
			rsMachines.Close
			Set rsMachines = Nothing
%>
                                </select>
                            </div>
                        </div>
<%
				Dim currentMapTop, currentMapLeft
				' Use printer-specific map coordinates (not machine coordinates)
				If IsNull(rs("printer_maptop")) Or rs("printer_maptop") = "" Then
					currentMapTop = "50"
				Else
					currentMapTop = rs("printer_maptop")
				End If
				If IsNull(rs("printer_mapleft")) Or rs("printer_mapleft") = "" Then
					currentMapLeft = "50"
				Else
					currentMapLeft = rs("printer_mapleft")
				End If
%>
                        <!-- Hidden coordinate fields - populated by map selector -->
                        <input type="hidden" id="maptop" name="maptop" value="<%=Server.HTMLEncode(currentMapTop)%>">
                        <input type="hidden" id="mapleft" name="mapleft" value="<%=Server.HTMLEncode(currentMapLeft)%>">

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Map Location: <span class="text-danger">*</span></label>
                            <div class="col-lg-9">
                                <button type="button" class="btn btn-secondary" id="selectLocationBtn">
                                    <i class="zmdi zmdi-pin"></i> Select Location on Map
                                </button>
                                <div id="coordinateDisplay" style="margin-top:10px; color:#aaa; font-size:13px;">
                                    Current position: X=<%=Server.HTMLEncode(currentMapLeft)%>, Y=<%=Server.HTMLEncode(currentMapTop)%>
                                </div>
                            </div>
                        </div>
                         <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label"></label>
                            <div class="col-lg-4">
				<BR>
                                <input type="submit" class="btn btn-primary" value="Update Printer">
                            </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
      </div>
      </div>
        
    </div>

	<!--start overlay-->
		  <div class="overlay toggle-menu"></div>
		<!--end overlay-->
	
    </div>
    <!-- End container-fluid-->
   </div><!--End content-wrapper-->
   <!--Start Back To Top Button-->
    <a href="javaScript:void();" class="back-to-top"><i class="fa fa-angle-double-up"></i> </a>
    <!--End Back To Top Button-->
	
	<!--Start footer-->
	<footer class="footer">
      <div class="container">
        <div class="text-center">
        </div>
      </div>
    </footer>
	<!--End footer-->
  </div><!--End wrapper-->


  <!-- Bootstrap core JavaScript-->
  <script src="assets/js/jquery.min.js"></script>
  <script src="assets/js/popper.min.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>
	
  <!-- simplebar js -->
  <script src="assets/plugins/simplebar/js/simplebar.js"></script>
  <!-- sidebar-menu js -->
  <script src="assets/js/sidebar-menu.js"></script>
  
  <!-- Custom scripts -->
  <script src="assets/js/app-script.js"></script>

  <!-- Location map popup modal -->
  <style>
  .content-wrapper {
      padding-bottom: 80px;
  }
  .footer {
      position: relative !important;
      bottom: auto !important;
  }

  /* Theme-specific styling for better visibility on all themes */
  body.bg-theme1 .location-link,
  body.bg-theme2 .location-link,
  body.bg-theme3 .location-link,
  body.bg-theme4 .location-link,
  body.bg-theme5 .location-link,
  body.bg-theme6 .location-link,
  body.bg-theme7 .location-link,
  body.bg-theme8 .location-link,
  body.bg-theme9 .location-link,
  body.bg-theme10 .location-link,
  body.bg-theme11 .location-link,
  body.bg-theme12 .location-link,
  body.bg-theme13 .location-link,
  body.bg-theme14 .location-link,
  body.bg-theme15 .location-link,
  body.bg-theme16 .location-link {
      color: #fff !important;
  }

  /* Toner refresh button - better visibility on all themes */
  body.bg-theme1 .btn-outline-primary,
  body.bg-theme2 .btn-outline-primary,
  body.bg-theme3 .btn-outline-primary,
  body.bg-theme4 .btn-outline-primary,
  body.bg-theme5 .btn-outline-primary,
  body.bg-theme6 .btn-outline-primary,
  body.bg-theme7 .btn-outline-primary,
  body.bg-theme8 .btn-outline-primary,
  body.bg-theme9 .btn-outline-primary,
  body.bg-theme10 .btn-outline-primary,
  body.bg-theme11 .btn-outline-primary,
  body.bg-theme12 .btn-outline-primary,
  body.bg-theme13 .btn-outline-primary,
  body.bg-theme14 .btn-outline-primary,
  body.bg-theme15 .btn-outline-primary,
  body.bg-theme16 .btn-outline-primary {
      background-color: rgba(255, 255, 255, 0.15) !important;
      color: #fff !important;
      border-color: rgba(255, 255, 255, 0.4) !important;
  }
  body.bg-theme1 .btn-outline-primary:hover,
  body.bg-theme2 .btn-outline-primary:hover,
  body.bg-theme3 .btn-outline-primary:hover,
  body.bg-theme4 .btn-outline-primary:hover,
  body.bg-theme5 .btn-outline-primary:hover,
  body.bg-theme6 .btn-outline-primary:hover,
  body.bg-theme7 .btn-outline-primary:hover,
  body.bg-theme8 .btn-outline-primary:hover,
  body.bg-theme9 .btn-outline-primary:hover,
  body.bg-theme10 .btn-outline-primary:hover,
  body.bg-theme11 .btn-outline-primary:hover,
  body.bg-theme12 .btn-outline-primary:hover,
  body.bg-theme13 .btn-outline-primary:hover,
  body.bg-theme14 .btn-outline-primary:hover,
  body.bg-theme15 .btn-outline-primary:hover,
  body.bg-theme16 .btn-outline-primary:hover {
      background-color: rgba(255, 255, 255, 0.3) !important;
  }

  /* Last updated text - better visibility on all themes */
  body.bg-theme1 .text-muted,
  body.bg-theme2 .text-muted,
  body.bg-theme3 .text-muted,
  body.bg-theme4 .text-muted,
  body.bg-theme5 .text-muted,
  body.bg-theme6 .text-muted,
  body.bg-theme7 .text-muted,
  body.bg-theme8 .text-muted,
  body.bg-theme9 .text-muted,
  body.bg-theme10 .text-muted,
  body.bg-theme11 .text-muted,
  body.bg-theme12 .text-muted,
  body.bg-theme13 .text-muted,
  body.bg-theme14 .text-muted,
  body.bg-theme15 .text-muted,
  body.bg-theme16 .text-muted {
      color: rgba(255, 255, 255, 0.8) !important;
  }

  /* Theme-specific popup header colors */
  body.bg-theme1 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme2 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme3 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme4 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme5 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme6 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme7 .location-popup-header { background: linear-gradient(45deg, #0c675e, #069e90); }
  body.bg-theme8 .location-popup-header { background: linear-gradient(45deg, #a52a04, #4f5f58); }
  body.bg-theme9 .location-popup-header { background: linear-gradient(45deg, #29323c, #485563); }
  body.bg-theme10 .location-popup-header { background: linear-gradient(45deg, #795548, #945c48); }
  body.bg-theme11 .location-popup-header { background: linear-gradient(45deg, #1565C0, #1E88E5); }
  body.bg-theme12 .location-popup-header { background: linear-gradient(45deg, #65379b, #886aea); }
  body.bg-theme13 .location-popup-header { background: linear-gradient(45deg, #ff5447, #f1076f); }
  body.bg-theme14 .location-popup-header { background: linear-gradient(45deg, #08a50e, #69bb03); }
  body.bg-theme15 .location-popup-header { background: linear-gradient(45deg, #6a11cb, #2575fc); }
  body.bg-theme16 .location-popup-header { background: linear-gradient(45deg, #6a11cb, #cccccc); }

  .location-popup-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 9998;
      display: none;
  }
  .location-popup {
      position: fixed;
      background: #1f1f1f;
      border: 2px solid #667eea;
      border-radius: 8px;
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.8);
      z-index: 9999;
      display: none;
      max-width: 90vw;
      max-height: 90vh;
  }
  .location-popup-header {
      background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 12px 15px;
      border-radius: 6px 6px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  .location-popup-close {
      background: none;
      border: none;
      color: white;
      font-size: 24px;
      cursor: pointer;
      padding: 0;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
  }
  .location-popup-close:hover {
      background: rgba(255, 255, 255, 0.2);
  }
  .location-popup-body {
      padding: 0;
      background: #2a2a2a;
  }
  .location-popup iframe {
      display: block;
      border: none;
      border-radius: 0 0 6px 6px;
  }
  .location-link:hover {
      text-decoration: underline;
  }
  </style>

  <script>
  $(document).ready(function() {
      // Create popup elements
      var $overlay = $('<div class="location-popup-overlay"></div>').appendTo('body');
      var $popup = $('<div class="location-popup"></div>').appendTo('body');

      $popup.html(
          '<div class="location-popup-header">' +
              '<h6 style="margin:0; font-size:16px;"><i class="zmdi zmdi-pin"></i> <span class="location-title">Loading...</span></h6>' +
              '<button class="location-popup-close" title="Close (Esc)">&times;</button>' +
          '</div>' +
          '<div class="location-popup-body">' +
              '<iframe src="" width="440" height="340"></iframe>' +
          '</div>'
      );

      var $iframe = $popup.find('iframe');
      var $title = $popup.find('.location-title');
      var currentPrinterId = null;

      // Function to show popup with smart positioning
      function showLocationPopup(printerId, locationName, mouseEvent) {
          if (currentPrinterId === printerId && $popup.is(':visible')) {
              return;
          }

          currentPrinterId = printerId;
          $title.text('Printer ' + locationName);
          $iframe.attr('src', './displaylocation.asp?type=printer&id=' + printerId);

          // Position popup using viewport coordinates
          var popupWidth = 440;
          var popupHeight = 400;
          var mouseX = mouseEvent.clientX;
          var mouseY = mouseEvent.clientY;
          var windowWidth = window.innerWidth;
          var windowHeight = window.innerHeight;

          var left, top;

          // Horizontal positioning
          left = mouseX + 10;
          if (left + popupWidth > windowWidth - 10) {
              left = mouseX - popupWidth - 10;
          }
          if (left < 10) {
              left = 10;
          }

          // Vertical positioning
          var spaceBelow = windowHeight - mouseY;
          var spaceAbove = mouseY;

          if (spaceBelow >= popupHeight + 20) {
              top = mouseY + 10;
          } else if (spaceAbove >= popupHeight + 20) {
              top = mouseY - popupHeight - 10;
          } else {
              top = Math.max(10, (windowHeight - popupHeight) / 2);
          }

          if (top < 10) {
              top = 10;
          }
          if (top + popupHeight > windowHeight - 10) {
              top = windowHeight - popupHeight - 10;
          }

          $popup.css({
              left: left + 'px',
              top: top + 'px',
              display: 'block'
          });

          $overlay.fadeIn(200);
          $popup.fadeIn(200);
      }

      function hideLocationPopup() {
          $overlay.fadeOut(200);
          $popup.fadeOut(200);
          setTimeout(function() {
              $iframe.attr('src', '');
              currentPrinterId = null;
          }, 200);
      }

      var hoverTimer = null;

      $('.location-link').on('mouseenter', function(e) {
          var $link = $(this);
          var printerId = $link.data('printerid');
          var locationName = $link.text().trim();
          var mouseEvent = e;

          if (hoverTimer) {
              clearTimeout(hoverTimer);
          }

          hoverTimer = setTimeout(function() {
              showLocationPopup(printerId, locationName, mouseEvent);
          }, 300);
      });

      $('.location-link').on('mouseleave', function() {
          if (hoverTimer) {
              clearTimeout(hoverTimer);
              hoverTimer = null;
          }
      });

      $popup.on('mouseenter', function() {
          // Keep popup open when hovering over it
      });

      $popup.on('mouseleave', function() {
          hideLocationPopup();
      });

      $overlay.on('click', hideLocationPopup);
      $popup.find('.location-popup-close').on('click', hideLocationPopup);

      $(document).on('keydown', function(e) {
          if (e.key === 'Escape' && $popup.is(':visible')) {
              hideLocationPopup();
          }
      });

      // Handle new model creation in edit form
      $('#addModelBtn, #modelid').on('change click', function() {
          if ($('#modelid').val() === 'new' || $(this).attr('id') === 'addModelBtn') {
              $('#modelid').val('new');
              $('#newModelSection').slideDown();
              $('#newmodelnumber').prop('required', true);
              $('#newvendorid').prop('required', true);
          }
      });

      $('#cancelNewModel').on('click', function() {
          $('#newModelSection').slideUp();
          $('#newVendorSection').slideUp();
          $('#modelid').val($('#modelid option:first').val());
          $('#newmodelnumber').val('').prop('required', false);
          $('#newvendorid').val('').prop('required', false);
          $('#newmodelnotes').val('');
          $('#newmodeldocpath').val('');
          $('#newvendorname').val('').prop('required', false);
      });

      // Show/hide new vendor section in edit form
      $('#addVendorBtn, #newvendorid').on('change click', function() {
          if ($('#newvendorid').val() === 'new' || $(this).attr('id') === 'addVendorBtn') {
              $('#newvendorid').val('new');
              $('#newVendorSection').slideDown();
              $('#newvendorname').prop('required', true);
          }
      });

      $('#cancelNewVendor').on('click', function() {
          $('#newVendorSection').slideUp();
          $('#newvendorid').val('');
          $('#newvendorname').val('').prop('required', false);
      });

      // Form validation for edit form
      $('form[action*="editprinter.asp"]').on('submit', function(e) {
          // If adding new model, make sure fields are filled
          if ($('#modelid').val() === 'new') {
              if ($('#newmodelnumber').val().trim() === '') {
                  e.preventDefault();
                  alert('Please enter a model number or select an existing model');
                  $('#newmodelnumber').focus();
                  return false;
              }
              if ($('#newvendorid').val() === '' || $('#newvendorid').val() === 'new') {
                  // If vendor is 'new', check vendor name
                  if ($('#newvendorid').val() === 'new') {
                      if ($('#newvendorname').val().trim() === '') {
                          e.preventDefault();
                          alert('Please enter a vendor name or select an existing vendor');
                          $('#newvendorname').focus();
                          return false;
                      }
                  } else {
                      e.preventDefault();
                      alert('Please select a vendor for the new model');
                      $('#newvendorid').focus();
                      return false;
                  }
              }
          }
      });
  });
  </script>

  <!-- Map Location Picker Modal -->
  <link rel="stylesheet" href="./leaflet/leaflet.css">
  <script src="./leaflet/leaflet.js"></script>

  <style>
  #mapPickerModal {
      display: none;
      position: fixed;
      z-index: 10000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.7);
  }
  #mapPickerContent {
      background-color: #1f1f1f;
      margin: 2% auto;
      padding: 0;
      border: 2px solid #667eea;
      border-radius: 8px;
      width: 70%;
      max-width: 900px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.8);
  }
  #mapPickerHeader {
      background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 6px 12px;
      border-radius: 6px 6px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  #mapPickerClose {
      background: none;
      border: none;
      color: white;
      font-size: 28px;
      cursor: pointer;
      padding: 0;
      width: 30px;
      height: 30px;
      line-height: 26px;
  }
  #mapPickerClose:hover {
      opacity: 0.8;
  }
  #mapPickerBody {
      padding: 0;
      background: #2a2a2a;
  }
  #locationPickerMap {
      width: 100%;
      height: 500px;
      background-color: #1a1a1a;
  }
  #mapPickerFooter {
      padding: 12px 15px;
      background: #1a1a1a;
      border-radius: 0 0 6px 6px;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  #selectedCoords {
      color: #aaa;
      font-size: 13px;
  }
  .map-picker-btn {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-left: 8px;
  }
  #confirmLocationBtn {
      background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
      color: white;
  }
  #confirmLocationBtn:hover {
      opacity: 0.9;
  }
  #cancelLocationBtn {
      background: #555;
      color: white;
  }
  #cancelLocationBtn:hover {
      background: #666;
  }
  </style>

  <div id="mapPickerModal">
      <div id="mapPickerContent">
          <div id="mapPickerHeader">
              <span style="font-size:14px; font-weight:600;"><i class="zmdi zmdi-pin"></i> Select Printer Location</span>
              <button id="mapPickerClose">&times;</button>
          </div>
          <div id="mapPickerBody">
              <div id="locationPickerMap"></div>
          </div>
          <div id="mapPickerFooter">
              <span id="selectedCoords">Click on the map to select a location</span>
              <div>
                  <button id="cancelLocationBtn" class="map-picker-btn">Cancel</button>
                  <button id="confirmLocationBtn" class="map-picker-btn">Confirm Location</button>
              </div>
          </div>
      </div>
  </div>

  <script>
  $(document).ready(function() {
      var pickerMap = null;
      var currentMarker = null;
      var selectedX = null;
      var selectedY = null;

      // Get current theme
      var bodyClass = document.body.className;
      var themeMatch = bodyClass.match(/bg-theme(\d+)/);
      var theme = themeMatch ? 'bg-theme' + themeMatch[1] : 'bg-theme1';

      // Theme-specific configurations
      var themeConfig = {
          'bg-theme1': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme2': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme3': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme4': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme5': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme6': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme7': { bg: '#0c675e', filter: 'brightness(0.8) contrast(1.1) hue-rotate(-10deg)' },
          'bg-theme8': { bg: '#4a3020', filter: 'brightness(0.75) contrast(1.1) saturate(0.8)' },
          'bg-theme9': { bg: '#29323c', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme10': { bg: '#795548', filter: 'brightness(0.8) contrast(1.05) sepia(0.2)' },
          'bg-theme11': { bg: '#1565C0', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)' },
          'bg-theme12': { bg: '#65379b', filter: 'brightness(0.8) contrast(1.1) hue-rotate(5deg)' },
          'bg-theme13': { bg: '#d03050', filter: 'brightness(0.85) contrast(1.05) saturate(0.9)' },
          'bg-theme14': { bg: '#2a7a2e', filter: 'brightness(0.8) contrast(1.1) saturate(0.95)' },
          'bg-theme15': { bg: '#4643d3', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)' },
          'bg-theme16': { bg: '#6a11cb', filter: 'brightness(0.8) contrast(1.1)' }
      };

      var config = themeConfig[theme] || { bg: '#1a1a1a', filter: 'brightness(0.7) contrast(1.1)' };

      // Determine which map image to use based on theme
      var lightThemes = ['bg-theme11', 'bg-theme13'];
      var mapImage = lightThemes.includes(theme) ? './images/sitemap2025-light.png' : './images/sitemap2025-dark.png';

      function updateCoordinateDisplay() {
          if (selectedX !== null && selectedY !== null) {
              var displayY = 2550 - selectedY;
              $('#selectedCoords').text('Selected: X=' + Math.round(selectedX) + ', Y=' + Math.round(displayY));
          } else {
              $('#selectedCoords').text('Click on the map to select a location');
          }
      }

      $('#selectLocationBtn').click(function() {
          $('#mapPickerModal').fadeIn(200);

          if (!pickerMap) {
              // Initialize map
              pickerMap = L.map('locationPickerMap', {
                  crs: L.CRS.Simple,
                  minZoom: -3
              });

              var bounds = [[0, 0], [2550, 3300]];
              var image = L.imageOverlay(mapImage, bounds);

              // Apply theme-specific filter
              image.on('load', function() {
                  var imgElement = this.getElement();
                  if (imgElement) {
                      imgElement.style.filter = config.filter;
                  }
              });

              image.addTo(pickerMap);
              pickerMap.fitBounds(bounds);

              // Add click handler
              pickerMap.on('click', function(e) {
                  selectedX = e.latlng.lng;
                  selectedY = e.latlng.lat;

                  // Remove existing marker
                  if (currentMarker) {
                      pickerMap.removeLayer(currentMarker);
                  }

                  // Add new draggable marker
                  currentMarker = L.marker([selectedY, selectedX], {
                      draggable: true,
                      icon: L.divIcon({
                          className: 'custom-marker-icon',
                          html: '<div style="width:20px; height:20px; background:#667eea; border:3px solid #fff; border-radius:50%; box-shadow:0 2px 8px rgba(0,0,0,0.5); cursor:move;"></div>',
                          iconSize: [20, 20],
                          iconAnchor: [10, 10]
                      })
                  }).addTo(pickerMap);

                  // Update coordinates when dragged
                  currentMarker.on('dragend', function(e) {
                      var position = e.target.getLatLng();
                      selectedX = position.lng;
                      selectedY = position.lat;
                      updateCoordinateDisplay();
                  });

                  updateCoordinateDisplay();
              });
          }

          // Load existing coordinates if available
          var existingLeft = $('#mapleft').val();
          var existingTop = $('#maptop').val();

          if (existingLeft && existingTop && existingLeft != '' && existingTop != '') {
              selectedX = parseFloat(existingLeft);
              selectedY = 2550 - parseFloat(existingTop);

              if (currentMarker) {
                  pickerMap.removeLayer(currentMarker);
              }

              currentMarker = L.marker([selectedY, selectedX], {
                  draggable: true,
                  icon: L.divIcon({
                      className: 'custom-marker-icon',
                      html: '<div style="width:20px; height:20px; background:#667eea; border:3px solid #fff; border-radius:50%; box-shadow:0 2px 8px rgba(0,0,0,0.5); cursor:move;"></div>',
                      iconSize: [20, 20],
                      iconAnchor: [10, 10]
                  })
              }).addTo(pickerMap);

              // Update coordinates when dragged
              currentMarker.on('dragend', function(e) {
                  var position = e.target.getLatLng();
                  selectedX = position.lng;
                  selectedY = position.lat;
                  updateCoordinateDisplay();
              });

              // Pan to marker
              pickerMap.panTo([selectedY, selectedX]);

              updateCoordinateDisplay();
          }

          setTimeout(function() {
              pickerMap.invalidateSize();
          }, 250);
      });

      $('#confirmLocationBtn').click(function() {
          if (selectedX !== null && selectedY !== null) {
              var convertedY = 2550 - selectedY;
              $('#mapleft').val(Math.round(selectedX));
              $('#maptop').val(Math.round(convertedY));

              // Update the display on the form
              $('#coordinateDisplay').html('Current position: X=' + Math.round(selectedX) + ', Y=' + Math.round(convertedY));

              updateCoordinateDisplay();
              $('#mapPickerModal').fadeOut(200);
          } else {
              alert('Please select a location on the map first.');
          }
      });

      $('#cancelLocationBtn, #mapPickerClose').click(function() {
          $('#mapPickerModal').fadeOut(200);
      });
  });
  </script>

</body>
</html>
<%
'=============================================================================
' CLEANUP
'=============================================================================
objConn.Close
%>