<!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
</head>

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

	pcid	=	Request.Querystring("pcid")

	strSQL 	=	"SELECT pc.*,vendors.*,models.*,pc_network_interfaces.*,machines.machineid,machines.machinenumber as machine_number,machines.alias,machines.machinetypeid,machinetypes.machinetype,machines.businessunitid,businessunits.businessunit,machines.printerid,printers.printerwindowsname,pctype.typename,functionalaccounts.functionalaccount,functionalaccounts.description as functionalaccount_description " & _
				"FROM pc " & _
				"LEFT JOIN models ON pc.modelnumberid=models.modelnumberid " & _
				"LEFT JOIN vendors ON models.vendorid=vendors.vendorid " & _
				"LEFT JOIN pc_network_interfaces ON pc_network_interfaces.pcid=pc.pcid " & _
				"LEFT JOIN machines ON pc.machinenumber = machines.machinenumber " & _
				"LEFT JOIN machinetypes ON machines.machinetypeid = machinetypes.machinetypeid " & _
				"LEFT JOIN businessunits ON machines.businessunitid = businessunits.businessunitid " & _
				"LEFT JOIN printers ON machines.printerid = printers.printerid " & _
				"LEFT JOIN pctype ON pc.pctypeid = pctype.pctypeid " & _
				"LEFT JOIN functionalaccounts ON pctype.functionalaccountid = functionalaccounts.functionalaccountid " & _
				"WHERE pc.isactive=1 AND pc.pcid="&pcid

	'response.write (strSQL)
	'response.end
	set rs = objconn.Execute(strSQL)

	' Check if PC exists
	IF rs.EOF THEN
		objConn.Close
		Response.Redirect("displaypcs.asp")
		Response.End
	END IF

	' Get machine ID if it exists
	IF NOT rs.EOF THEN
		IF NOT IsNull(rs("machineid")) THEN
			machineid = rs("machineid")
		ELSE
			machineid = 0
		END IF
	END IF
%>

<body class="bg-theme <%Response.Write(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/computers/<%Response.Write(rs("image"))%>" alt="Card image cap">
            </div>
            <div class="card-body pt-5">
                <img src="./images/computers/<%Response.Write(rs("image"))%>" alt="profile-image" class="profile">
             	<h5 class="card-title"><%Response.Write(rs("vendor"))%></h5>
            </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="#applications" data-toggle="pill" class="nav-link"><i class="zmdi zmdi-apps"></i> <span class="hidden-xs">Applications</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>Hostname:</strong></p>
                            <p class="mb-2"><strong>Location:</strong></p>
                            <p class="mb-2"><strong>IP:</strong></p>
                            <p class="mb-2"><strong>Functional Account:</strong></p>
                        </div>
                        <div class="col-md-5">
                            <p class="mb-2"><%Response.Write(rs("vendor"))%></p>
                            <p class="mb-2"><%Response.Write(rs("modelnumber"))%></p>
                            <p class="mb-2"><%Response.Write(rs("serialnumber"))%></p>
                            <p class="mb-2"><a href="com.realvnc.vncviewer.connect://<%Response.Write(rs("ipaddress"))%>:5900" title="VNC To Desktop"><%Response.Write(rs("hostname"))%></a></p>
                            <p class="mb-2">
<%
	IF machineid > 0 THEN
		Dim locationDisplay
		' Use alias if available, otherwise machine_number
		IF NOT IsNull(rs("alias")) AND rs("alias") <> "" THEN
			locationDisplay = rs("alias")
		ELSE
			locationDisplay = rs("machine_number")
		END IF
		Response.Write("<span class='location-link' data-machineid='" & machineid & "' style='cursor:pointer; color:#007bff;'><i class='zmdi zmdi-pin' style='margin-right:4px;'></i>" & locationDisplay & "</span>")
	ELSE
		Response.Write("<span class='text-muted'>Not assigned</span>")
	END IF
%>
                            </p>
                            <p class="mb-2">
<%
	IF NOT IsNull(rs("ipaddress")) AND rs("ipaddress") <> "" THEN
		Response.Write(rs("ipaddress"))
	ELSE
		Response.Write("<span class='text-muted'>N/A</span>")
	END IF
%>
                            </p>
                            <p class="mb-2">
<%
	IF NOT IsNull(rs("functionalaccount")) AND rs("functionalaccount") <> "" THEN
		Dim accountDisplay, descDisplay, extractedAccount
		Dim pcTypeName
		pcTypeName = ""
		IF NOT IsNull(rs("typename")) THEN
			pcTypeName = UCase(Trim(rs("typename") & ""))
		END IF

		' Check if loggedinuser exists and should be used
		Dim useLoggedInUser
		useLoggedInUser = False
		IF NOT IsNull(rs("LoggedInUser")) AND rs("LoggedInUser") <> "" THEN
			' Use loggedinuser for Standard, Engineer, or TBD types
			IF pcTypeName = "STANDARD" OR pcTypeName = "ENGINEER" OR rs("functionalaccount") = "TBD" OR rs("functionalaccount") = "1" THEN
				useLoggedInUser = True
			END IF
		END IF

		IF useLoggedInUser THEN
			accountDisplay = rs("LoggedInUser")

			' Try to extract the account number from loggedinuser (format: lg[account]sd)
			Dim loggedUser
			loggedUser = rs("LoggedInUser")
			IF Left(loggedUser, 2) = "lg" AND Right(loggedUser, 2) = "sd" AND Len(loggedUser) > 4 THEN
				extractedAccount = Mid(loggedUser, 3, Len(loggedUser) - 4)
			ELSE
				extractedAccount = ""
			END IF
		ELSE
			accountDisplay = "lg" & rs("functionalaccount") & "sd"
			extractedAccount = ""
		END IF

		' Determine what description to show
		Dim descField
		descField = ""

		' If showing plain SSO (not lg[account]sd format), label it as "SSO"
		IF useLoggedInUser AND extractedAccount = "" THEN
			descField = "SSO"
		' If we extracted an account from loggedinuser, look up its description
		ELSEIF extractedAccount <> "" THEN
			Dim rsDesc, sqlDesc
			sqlDesc = "SELECT description FROM functionalaccounts WHERE functionalaccount = '" & Replace(extractedAccount, "'", "''") & "' AND isactive = 1"
			Set rsDesc = objConn.Execute(sqlDesc)
			IF NOT rsDesc.EOF THEN
				IF NOT IsNull(rsDesc("description")) AND rsDesc("description") <> "" THEN
					descField = rsDesc("description") & ""
				END IF
			END IF
			rsDesc.Close
			Set rsDesc = Nothing
		' Otherwise use functional account description from the query
		ELSE
			On Error Resume Next
			descField = rs("functionalaccount_description") & ""
			If descField = "" Then
				descField = rs("description") & ""
			End If
			On Error Goto 0
		END IF

		IF descField <> "" AND NOT IsNull(descField) THEN
			descDisplay = " - " & descField
		ELSE
			descDisplay = ""
		END IF

		Response.Write(accountDisplay & descDisplay)
	ELSE
		Response.Write("<span class='text-muted'>N/A</span>")
	END IF
%>
                            </p>
                        </div>
                    </div>

                    <hr style="margin:20px 0;">

                    <h5 class="mb-3">Warranty Information</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <p class="mb-2"><strong>Status:</strong></p>
                            <p class="mb-2"><strong>End Date:</strong></p>
                            <p class="mb-2"><strong>Days Remaining:</strong></p>
                            <p class="mb-2"><strong>Service Level:</strong></p>
                            <p class="mb-2"><strong>Last Checked:</strong></p>
                        </div>
                        <div class="col-md-9">
<%
Dim warrantyStatus, warrantyEndDate, warrantyDaysRemaining, warrantyServiceLevel, warrantyLastChecked
Dim warrantyStatusClass, warrantyBadge

warrantyStatus = rs("warrantystatus")
warrantyEndDate = rs("warrantyenddate")
warrantyDaysRemaining = rs("warrantydaysremaining")
warrantyServiceLevel = rs("warrantyservicelevel")
warrantyLastChecked = rs("warrantylastchecked")

' Determine warranty status badge
If IsNull(warrantyStatus) Or warrantyStatus = "" Then
    warrantyBadge = "<span class='badge badge-secondary'>Unknown</span>"
ElseIf LCase(warrantyStatus) = "active" Then
    If Not IsNull(warrantyDaysRemaining) And IsNumeric(warrantyDaysRemaining) Then
        If warrantyDaysRemaining < 30 Then
            warrantyBadge = "<span class='badge badge-warning'>Expiring Soon</span>"
        Else
            warrantyBadge = "<span class='badge badge-success'>Active</span>"
        End If
    Else
        warrantyBadge = "<span class='badge badge-success'>Active</span>"
    End If
ElseIf LCase(warrantyStatus) = "expired" Then
    warrantyBadge = "<span class='badge badge-danger'>Expired</span>"
Else
    warrantyBadge = "<span class='badge badge-info'>" & warrantyStatus & "</span>"
End If
%>
                            <p class="mb-2"><%Response.Write(warrantyBadge)%></p>
                            <p class="mb-2">
<%
If Not IsNull(warrantyEndDate) And warrantyEndDate <> "" And warrantyEndDate <> "0000-00-00" Then
    Response.Write(warrantyEndDate)
Else
    Response.Write("<span class='text-muted'>Not available</span>")
End If
%>
                            </p>
                            <p class="mb-2">
<%
If Not IsNull(warrantyDaysRemaining) And IsNumeric(warrantyDaysRemaining) Then
    If warrantyDaysRemaining < 0 Then
        Response.Write("<span class='text-danger'>" & Abs(warrantyDaysRemaining) & " days overdue</span>")
    ElseIf warrantyDaysRemaining < 30 Then
        Response.Write("<span class='text-warning'>" & warrantyDaysRemaining & " days</span>")
    Else
        Response.Write(warrantyDaysRemaining & " days")
    End If
Else
    Response.Write("<span class='text-muted'>Not available</span>")
End If
%>
                            </p>
                            <p class="mb-2">
<%
If Not IsNull(warrantyServiceLevel) And warrantyServiceLevel <> "" Then
    Response.Write(warrantyServiceLevel)
Else
    Response.Write("<span class='text-muted'>Not available</span>")
End If
%>
                            </p>
                            <p class="mb-2">
<%
If Not IsNull(warrantyLastChecked) And warrantyLastChecked <> "" Then
    Response.Write(warrantyLastChecked)
Else
    Response.Write("<span class='text-muted'>Never checked</span>")
End If
%>
                            </p>
                        </div>
                    </div>
                </div>
                <div class="tab-pane" id="applications">
                  <div class="table-responsive">
                    <table class="table table-hover table-striped">
                        <tbody>
<%

			IF machineid > 0 THEN
				strSQL2	=	"SELECT * FROM installedapps,applications WHERE installedapps.appid=applications.appid AND installedapps.isactive=1 AND " &_
							"installedapps.machineid=" & machineid & " ORDER BY appname ASC"
				set rs2 = objconn.Execute(strSQL2)
				while not rs2.eof
					Response.Write("<tr><td><span class='float-left font-weight-bold'>"&rs2("appname")&"</span></td></tr>")
					rs2.movenext
				wend
			ELSE
				Response.Write("<tr><td class='text-muted'>No machine assigned - cannot display installed applications</td></tr>")
			END IF

%>                      
                        </tbody> 
                    </table>
                  </div>
                </div>
                <div class="tab-pane" id="edit">
  			<form method="post" action="./updatepc_direct.asp" id="pcEditForm">
                        <input type="hidden" name="pcid" value="<%=pcid%>">
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Vendor:</label>
                            <div class="col-lg-9">
                              <div class="input-group">
                                <select name="vendorid" id="pcvendorid" class="form-control">
						<option value='<%response.write(rs("vendorid"))%>'><%Response.Write(rs("vendor"))%></option>
                                        <option value="new">+ Add New Vendor</option>
<%
			strSQL2	=	"Select * from vendors where ispc=1 and isactive=1 order by vendor ASC"
			set rs2 = objconn.Execute(strSQL2)
			while not rs2.eof
					Response.Write("<option value='"&rs2("vendorid")&"'>"&rs2("vendor")&"</option>")
			rs2.movenext
			wend
%>
				</select>
                                <div class="input-group-append">
                                  <button type="button" class="btn btn-info" id="addPCVendorBtn">
                                    <i class="zmdi zmdi-plus"></i> New
                                  </button>
                                </div>
                              </div>
                            </div>
                        </div>

                        <!-- New Vendor Fields (hidden by default) -->
                        <div id="newPCVendorSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #28a745; background-color:rgba(40,167,69,0.05); margin-bottom:15px;">
                          <h6 style="color:#28a745; margin-bottom:15px;"><i class="zmdi zmdi-plus-circle"></i> New PC Vendor</h6>
                          <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Vendor Name:</label>
                            <div class="col-lg-9">
                              <input type="text" class="form-control" id="newpcvendorname" name="newpcvendorname" placeholder="e.g., Dell, HP, Lenovo">
                            </div>
                          </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="pcmodelid" class="form-control">
						<option value='<%response.write(rs("modelnumberid"))%>'><%Response.Write(rs("modelnumber"))%></option>
                                        <option value="new">+ Add New Model</option>
<%
			strSQL2	=	"Select * from vendors,models WHERE " & _
						"models.vendorid	=	vendors.vendorid AND " & _
						"vendors.ispc=1 AND models.isactive=1 ORDER BY modelnumber ASC"
			set rs2 = objconn.Execute(strSQL2)
			while not rs2.eof
					Response.Write("<option value='"&rs2("modelnumberid")&"'>"&rs2("modelnumber")&"</option>")
			rs2.movenext
			wend
%>
				</select>
                                <div class="input-group-append">
                                  <button type="button" class="btn btn-info" id="addPCModelBtn">
                                    <i class="zmdi zmdi-plus"></i> New
                                  </button>
                                </div>
                              </div>
                            </div>
                        </div>

                        <!-- New Model Fields (hidden by default) -->
                        <div id="newPCModelSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #007bff; background-color:rgba(0,123,255,0.05); margin-bottom:15px;">
                          <h6 style="color:#007bff; margin-bottom:15px;"><i class="zmdi zmdi-plus-circle"></i> New PC Model</h6>
                          <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Model Number:</label>
                            <div class="col-lg-9">
                              <input type="text" class="form-control" id="newpcmodelnumber" name="newpcmodelnumber" placeholder="e.g., OptiPlex 7090">
                            </div>
                          </div>
                          <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Select Vendor:</label>
                            <div class="col-lg-9">
                              <select class="form-control" id="newpcmodelvendorid" name="newpcmodelvendorid">
                                <option value="">-- Select Vendor First --</option>
<%
			Dim rs3, strSQL3
			strSQL3	=	"Select * from vendors where ispc=1 and isactive=1 order by vendor ASC"
			set rs3 = objconn.Execute(strSQL3)
			while not rs3.eof
					Response.Write("<option value='"&rs3("vendorid")&"'>"&rs3("vendor")&"</option>")
			rs3.movenext
			wend
%>
                              </select>
                              <small class="form-text text-muted">Select existing vendor or create new one above</small>
                            </div>
                          </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Machine:</label>
                            <div class="col-lg-9">
                            <select name="machinenumber" class="form-control">
<%
			IF NOT IsNull(rs("machine_number")) AND rs("machine_number") <> "" THEN
				IF NOT IsNull(rs("alias")) AND rs("alias") <> "" THEN
					Response.Write("<option value='" & rs("machine_number") & "'>" & rs("alias") & " (" & rs("machine_number") & ")</option>")
				ELSE
					Response.Write("<option value='" & rs("machine_number") & "'>" & rs("machine_number") & "</option>")
				END IF
			ELSE
				Response.Write("<option value=''>-- Not Assigned --</option>")
			END IF

			strSQL2	=	"SELECT machinenumber, alias FROM machines WHERE isactive=1 ORDER BY machinenumber ASC"
			set rs2 = objconn.Execute(strSQL2)
			while not rs2.eof
				IF NOT IsNull(rs2("alias")) AND rs2("alias") <> "" THEN
					Response.Write("<option value='" & rs2("machinenumber") & "'>" & rs2("alias") & " (" & rs2("machinenumber") & ")</option>")
				ELSE
					Response.Write("<option value='" & rs2("machinenumber") & "'>" & rs2("machinenumber") & "</option>")
				END IF
				rs2.movenext
			wend
%>
				</select>
                            </div>
                        </div>
                        <!-- Function, BU, and Printer fields commented out - they modify machines table, not pc table -->
                        <!--
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Function:</label>
                            <div class="col-lg-9">
                            <select name="machinetypeid" class="form-control" disabled>
						<option value='<%response.write(rs("machinetypeid"))%>'><%Response.Write(rs("machinetype"))%></option>
<%
			strSQL2	=	"Select * FROM machinetypes WHERE machinetypes.isactive=1 ORDER BY machinetype  ASC"
			set rs2 = objconn.Execute(strSQL2)
			while not rs2.eof
					Response.Write("<option value='"&rs2("machinetypeid")&"'>"&rs2("machinetype")&"</option>")
			rs2.movenext
			wend
%>
				</select>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">BU:</label>
                            <div class="col-lg-9">
                            <select name="businessunitid" class="form-control" disabled>
						<option value='<%response.write(rs("businessunitid"))%>'><%Response.Write(rs("businessunit"))%></option>
<%
			strSQL2	=	"Select * FROM businessunits WHERE businessunits.isactive=1 ORDER BY businessunit  ASC"
			set rs2 = objconn.Execute(strSQL2)
			while not rs2.eof
					Response.Write("<option value='"&rs2("businessunitid")&"'>"&rs2("businessunit")&"</option>")
			rs2.movenext
			wend
%>
				</select>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Printer:</label>
                            <div class="col-lg-9">
                            <select name="printerid" class="form-control" disabled>
						<option value='<%response.write(rs("printerid"))%>'><%Response.Write(rs("printerwindowsname"))%></option>
<%
			strSQL2	=	"Select * FROM printers,models WHERE printers.modelid=models.modelnumberid AND printers.isactive=1 ORDER BY printerwindowsname  ASC"
			set rs2 = objconn.Execute(strSQL2)
			while not rs2.eof
					Response.Write("<option value='"&rs2("printerid")&"'>"&rs2("printerwindowsname")&" - " &rs2("modelnumber")&"</option>")
			rs2.movenext
			wend
%>
				</select>
                            </div>
                        </div>
                        -->
                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label"></label>
                            <div class="col-lg-9">
                                <input type="reset" class="btn btn-secondary" value="Cancel">
                                <input type="submit" class="btn btn-primary" value="Save Changes">
                            </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;
  }

  .location-link:hover {
      text-decoration: underline;
  }

  /* 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;
  }
  </style>

  <script>
  $(document).ready(function() {
      console.log('Location hover script loaded');
      console.log('Found location links:', $('.location-link').length);

      // 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 currentMachineId = null;

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

          currentMachineId = machineId;
          $title.text(locationName);
          $iframe.attr('src', './displaylocation.asp?machineid=' + machineId);

          // 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', '');
              currentMachineId = null;
          }, 200);
      }

      var hoverTimer = null;

      $('.location-link').on('mouseenter', function(e) {
          console.log('Mouse entered location link');
          var $link = $(this);
          var machineId = $link.data('machineid');
          var locationName = $link.text().trim();
          var mouseEvent = e;

          console.log('Machine ID:', machineId, 'Location:', locationName);

          if (hoverTimer) {
              clearTimeout(hoverTimer);
          }

          hoverTimer = setTimeout(function() {
              console.log('Showing popup after 300ms delay');
              showLocationPopup(machineId, 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();
          }
      });

      // PC Vendor dropdown change handler
      $('#pcvendorid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newPCVendorSection').slideDown();
          } else {
              $('#newPCVendorSection').slideUp();
          }
      });

      // PC Vendor "+ New" button
      $('#addPCVendorBtn').on('click', function() {
          $('#pcvendorid').val('new').trigger('change');
      });

      // PC Model dropdown change handler
      $('#pcmodelid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newPCModelSection').slideDown();
          } else {
              $('#newPCModelSection').slideUp();
          }
      });

      // PC Model "+ New" button
      $('#addPCModelBtn').on('click', function() {
          $('#pcmodelid').val('new').trigger('change');
      });

      // When creating new vendor, automatically sync to model's vendor dropdown
      $('#pcvendorid').on('change', function() {
          var selectedVendorId = $(this).val();
          if (selectedVendorId !== 'new' && selectedVendorId !== '') {
              // Update the model vendor dropdown to match
              $('#newpcmodelvendorid').val(selectedVendorId);
          }
      });
  });
  </script>

</body>
</html>
<% 	objConn.Close %>