<!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
  <link rel="stylesheet" href="./leaflet/leaflet.css">
  <script src="./leaflet/leaflet.js"></script>
</head>

<%
	theme = Request.Cookies("theme")
	If theme = "" Then
		theme = "bg-theme1"
	End If

	' Get and validate machineid parameter
	Dim machineid
	machineid = Trim(Request.Querystring("machineid"))

	' Validate machine ID
	If Not IsNumeric(machineid) Or CLng(machineid) < 1 Then
		Response.Redirect("default.asp")
		Response.End
	End If

	' Use LEFT JOINs so query returns data even if printer/PC not associated
	strSQL = "SELECT machines.*, machinetypes.*, models.*, businessunits.*, vendors.*, functionalaccounts.*, " & _
			"printers.ipaddress AS printerip, printers.printerid, printers.printercsfname, printers.printerwindowsname, " & _
			"pc.pcid, pc.hostname, pc.loggedinuser AS LoggedInUser, pc_network_interfaces.IPAddress AS pcip " & _
			"FROM machines " & _
			"INNER JOIN machinetypes ON machines.machinetypeid = machinetypes.machinetypeid " & _
			"INNER JOIN models ON machines.modelnumberid = models.modelnumberid " & _
			"INNER JOIN businessunits ON machines.businessunitid = businessunits.businessunitid " & _
			"INNER JOIN functionalaccounts ON machinetypes.functionalaccountid = functionalaccounts.functionalaccountid " & _
			"INNER JOIN vendors ON models.vendorid = vendors.vendorid " & _
			"LEFT JOIN printers ON machines.printerid = printers.printerid " & _
			"LEFT JOIN pc ON pc.machinenumber = machines.machinenumber " & _
			"LEFT JOIN pc_network_interfaces ON pc_network_interfaces.pcid = pc.pcid AND pc_network_interfaces.DefaultGateway IS NOT NULL " & _
			"WHERE machines.machineid = " & CLng(machineid)

	Set rs = objConn.Execute(strSQL)

	' Check if machine exists
	If rs.EOF Then
		rs.Close
		Set rs = Nothing
		Response.Redirect("default.asp")
		Response.End
	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/machines/<%If Not IsNull(rs("image")) Then Response.Write(Server.HTMLEncode(rs("image"))) Else Response.Write("default.png") End If%>" alt="Card image cap">
            </div>
            <div class="card-body pt-5">
                <img src="./images/machines/<%If Not IsNull(rs("image")) Then Response.Write(Server.HTMLEncode(rs("image"))) Else Response.Write("default.png") End If%>" alt="profile-image" class="profile">
                <h5 class="card-title"><%If Not IsNull(rs("machinenumber")) Then Response.Write(Server.HTMLEncode(rs("machinenumber"))) End If%></h5>
          	<h5 class="card-title"><%If Not IsNull(rs("vendor")) Then Response.Write(Server.HTMLEncode(rs("vendor"))) End If%></h5>
                <h5 class="card-text"><%If Not IsNull(rs("machinetype")) Then Response.Write(Server.HTMLEncode(rs("machinetype"))) End If%></h5>
                <p class="card-text"><%If Not IsNull(rs("machinedescription")) Then Response.Write(Server.HTMLEncode(rs("machinedescription"))) End If%></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="#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>Location:</strong></p>
                            <p class="mb-2"><strong>Vendor:</strong></p>
                            <p class="mb-2"><strong>Model:</strong></p>
                            <p class="mb-2"><strong>Function:</strong></p>
                            <p class="mb-2"><strong>BU:</strong></p>
                            <p class="mb-2"><strong>PC:</strong></p>
                            <p class="mb-2"><strong>IP:</strong></p>
                            <p class="mb-2"><strong>User:</strong></p>
                            <p class="mb-2"><strong>Printer:</strong></p>
                            <p>

                            </p>
                        </div>
                        <div class="col-md-5">
                            <p class="mb-2">
                                <span class="location-link" data-machineid="<%Response.Write(machineid)%>" style="cursor:pointer; color:#007bff;">
                                    <i class="zmdi zmdi-pin" style="margin-right:4px;"></i><%Response.Write(rs("machinenumber"))%>
                                </span>
                            </p>
                            <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("machinetype"))%></p>
                            <p class="mb-2"><%Response.Write(rs("businessunit"))%></p>
<%
' PC data - check if exists (LEFT JOIN may return NULL)
If Not IsNull(rs("pcip")) And rs("pcip") <> "" Then
    Response.Write("<p class='mb-2'><a href='com.realvnc.vncviewer.connect://" & rs("pcip") & ":5900' title='VNC To Desktop'>" & rs("hostname") & "</a></p>")
    Response.Write("<p class='mb-2'>" & rs("pcip") & "</p>")
    If Not IsNull(rs("LoggedInUser")) Then
        Response.Write("<p class='mb-2'>" & rs("LoggedInUser") & "</p>")
    Else
        Response.Write("<p class='mb-2'>&nbsp;</p>")
    End If
Else
    Response.Write("<p class='mb-2'>No PC assigned</p>")
    Response.Write("<p class='mb-2'>&nbsp;</p>")
    Response.Write("<p class='mb-2'>&nbsp;</p>")
End If

' Printer data - check if exists (LEFT JOIN may return NULL)
If Not IsNull(rs("printerid")) And rs("printerid") <> "" Then
    Response.Write("<p class='mb-2'><a href='./displayprinter.asp?printerid=" & rs("printerid") & "'>" & rs("printerwindowsname") & "</a></p>")
Else
    Response.Write("<p class='mb-2'>No printer assigned</p>")
End If
%>
                        </div>
                        <div class="col-md-12">
                             <div class="table-responsive">
                          </div>
                        </div>
                    </div>
                    <!--/row-->
                </div>
                <div class="tab-pane" id="applications">
                  <div class="table-responsive">
                    <table class="table table-hover table-striped">
                        <tbody>
<%
			strSQL2 = "SELECT * FROM installedapps, applications WHERE installedapps.appid = applications.appid AND installedapps.isactive = 1 AND installedapps.machineid = " & CLng(machineid) & " ORDER BY appname ASC"
			Set rs2 = objConn.Execute(strSQL2)
			Do While Not rs2.EOF
				Response.Write("<tr><td><span class='float-left font-weight-bold'>" & Server.HTMLEncode(rs2("appname")) & "</span></td></tr>")
				rs2.MoveNext
			Loop
			rs2.Close
			Set rs2 = Nothing
%>
                        </tbody>
                    </table>
                  </div>
                </div>
                <div class="tab-pane" id="edit">
  			<form method="post" action="./editmacine.asp?machineid=<%=Server.HTMLEncode(machineid)%>">
                        <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='<%response.write(rs("vendorid"))%>'><%Response.Write(rs("vendor"))%></option>
<%
			strSQL2	=	"Select * from vendors where ismachine=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>
                        </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='<%response.write(rs("modelnumberid"))%>'><%Response.Write(rs("modelnumber"))%></option>
<%
			strSQL2	=	"Select * from vendors,models WHERE " & _
						"models.vendorid	=	vendors.vendorid AND " & _
						"vendors.ismachine=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
%>
					<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>

                                <!-- Slide-down section for adding new model -->
                                <div id="newModelSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #667eea; background-color:rgba(102,126,234,0.05); margin-bottom:15px;">
                                    <h6 class="mb-3"><i class="zmdi zmdi-plus-circle"></i> New Machine 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., ThinkPad T14">
                                    </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
    strSQL2 = "SELECT vendorid, vendor FROM vendors WHERE ismachine = 1 AND isactive = 1 ORDER BY vendor ASC"
    Set rsVendorsEdit = objConn.Execute(strSQL2)
    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>

                                    <!-- Nested vendor creation section -->
                                    <div id="newVendorSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #764ba2; background-color:rgba(118,75,162,0.05); 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., Dell, Lenovo, HP">
                                        </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="newmodelimage">Image Filename (Optional)</label>
                                        <input type="text" class="form-control" id="newmodelimage" name="newmodelimage"
                                               maxlength="255" placeholder="e.g., thinkpad-t14.jpg">
                                    </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">Function:</label>
                            <div class="col-lg-9">
                            <div class="input-group">
                            <select name="machinetypeid" id="machinetypeid" class="form-control">
						<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
%>
					<option value="new">+ Add New Machine Type</option>
				</select>
				<div class="input-group-append">
					<button type="button" class="btn btn-info" id="addMachineTypeBtn">
						<i class="zmdi zmdi-plus"></i> New
					</button>
				</div>
				</div>

                                <!-- Slide-down section for adding new machine type -->
                                <div id="newMachineTypeSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #667eea; background-color:rgba(102,126,234,0.05); margin-bottom:15px;">
                                    <h6 class="mb-3"><i class="zmdi zmdi-plus-circle"></i> New Machine Type</h6>

                                    <div class="form-group">
                                        <label for="newmachinetypename">Machine Type Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="newmachinetypename" name="newmachinetypename"
                                               maxlength="50" placeholder="e.g., Laptop, Desktop, Server">
                                    </div>

                                    <div class="form-group">
                                        <label for="newmachinetypedescription">Description (Optional)</label>
                                        <textarea class="form-control" id="newmachinetypedescription" name="newmachinetypedescription"
                                                  rows="2" maxlength="255"
                                                  placeholder="Additional notes about this machine type..."></textarea>
                                    </div>

                                    <div class="form-group">
                                        <label for="newfunctionalaccountid">Functional Account <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                        <select class="form-control" id="newfunctionalaccountid" name="newfunctionalaccountid">
                                            <option value="">-- Select Functional Account --</option>
<%
    Dim rsFunctionalAccountsEdit
    strSQL2 = "SELECT functionalaccountid, functionalaccount FROM functionalaccounts WHERE isactive = 1 ORDER BY functionalaccount ASC"
    Set rsFunctionalAccountsEdit = objConn.Execute(strSQL2)
    While Not rsFunctionalAccountsEdit.EOF
        Response.Write("<option value='" & rsFunctionalAccountsEdit("functionalaccountid") & "'>" & Server.HTMLEncode(rsFunctionalAccountsEdit("functionalaccount")) & "</option>")
        rsFunctionalAccountsEdit.MoveNext
    Wend
    rsFunctionalAccountsEdit.Close
    Set rsFunctionalAccountsEdit = Nothing
%>
                                            <option value="new">+ Add New Functional Account</option>
                                        </select>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-info" id="addFunctionalAccountBtn">
                                                <i class="zmdi zmdi-plus"></i> New
                                            </button>
                                        </div>
                                        </div>
                                    </div>

                                    <!-- Nested functional account creation section -->
                                    <div id="newFunctionalAccountSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #764ba2; background-color:rgba(118,75,162,0.05); margin-bottom:15px;">
                                        <h6 class="mb-3"><i class="zmdi zmdi-plus-circle"></i> New Functional Account</h6>

                                        <div class="form-group">
                                            <label for="newfunctionalaccountname">Functional Account Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="newfunctionalaccountname" name="newfunctionalaccountname"
                                                   maxlength="50" placeholder="e.g., IT, Finance, HR">
                                        </div>

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

                                    <button type="button" class="btn btn-sm btn-secondary" id="cancelNewMachineType">
                                        <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">BU:</label>
                            <div class="col-lg-9">
                            <div class="input-group">
                            <select name="businessunitid" id="businessunitid" class="form-control">
						<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
%>
					<option value="new">+ Add New Business Unit</option>
				</select>
				<div class="input-group-append">
					<button type="button" class="btn btn-info" id="addBusinessUnitBtn">
						<i class="zmdi zmdi-plus"></i> New
					</button>
				</div>
				</div>

                                <!-- Slide-down section for adding new business unit -->
                                <div id="newBusinessUnitSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #667eea; background-color:rgba(102,126,234,0.05); margin-bottom:15px;">
                                    <h6 class="mb-3"><i class="zmdi zmdi-plus-circle"></i> New Business Unit</h6>

                                    <div class="form-group">
                                        <label for="newbusinessunitname">Business Unit Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="newbusinessunitname" name="newbusinessunitname"
                                               maxlength="50" placeholder="e.g., Engineering, Sales, Operations">
                                    </div>

                                    <button type="button" class="btn btn-sm btn-secondary" id="cancelNewBusinessUnit">
                                        <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">Printer:</label>
                            <div class="col-lg-9">
                            <select name="printerid" class="form-control">
<%
' Show current printer if exists
If Not IsNull(rs("printerid")) And rs("printerid") <> "" Then
    Response.Write("<option value='" & rs("printerid") & "'>" & rs("printerwindowsname") & "</option>")
Else
    Response.Write("<option value=''>-- No printer assigned --</option>")
End If
%>
<%
			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>
                        <!-- Hidden coordinate fields - populated by map selector -->
                        <input type="hidden" id="mapleft" name="mapleft" value="<%Response.Write(rs("mapleft"))%>">
                        <input type="hidden" id="maptop" name="maptop" value="<%Response.Write(rs("maptop"))%>">

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Map Location:</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=<%Response.Write(rs("mapleft"))%>, Y=<%Response.Write(rs("maptop"))%>
                                </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 Machine">
                            </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 */
  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;
  }

  /* 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() {
      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 showLocationPopup(machineId, locationName, mouseEvent) {
          if (currentMachineId === machineId && $popup.is(':visible')) {
              return;
          }

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

          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;

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

          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) {
          var $link = $(this);
          var machineId = $link.data('machineid');
          var locationName = $link.text().trim();
          var mouseEvent = e;

          if (hoverTimer) {
              clearTimeout(hoverTimer);
          }

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

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

      $popup.on('mouseenter', function() {});
      $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();
          }
      });
  });
  </script>

  <!-- Map Location Picker Modal -->
  <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: 24px;
      cursor: pointer;
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
  }
  #mapPickerClose:hover {
      background: rgba(255, 255, 255, 0.2);
  }
  #mapPickerBody {
      padding: 12px;
      background: #2a2a2a;
  }
  #locationPickerMap {
      width: 100%;
      height: 400px;
      background: #1a1a1a;
      border-radius: 4px;
  }
  #mapPickerFooter {
      padding: 10px 15px;
      background: #1f1f1f;
      border-top: 1px solid #444;
      border-radius: 0 0 6px 6px;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  #selectedCoords {
      color: #aaa;
      font-size: 14px;
  }
  .map-picker-btn {
      padding: 8px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-left: 10px;
  }
  #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 Machine 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 marker
                  currentMarker = L.circleMarker([selectedY, selectedX], {
                      radius: 8,
                      fillColor: '#667eea',
                      color: '#fff',
                      weight: 2,
                      opacity: 1,
                      fillOpacity: 0.8
                  }).addTo(pickerMap);

                  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.circleMarker([selectedY, selectedX], {
                  radius: 8,
                  fillColor: '#667eea',
                  color: '#fff',
                  weight: 2,
                  opacity: 1,
                  fillOpacity: 0.8
              }).addTo(pickerMap);

              // 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);
      });

      // ========================================
      // Nested Creation Form Handlers
      // ========================================

      // Button handlers to trigger dropdown selection
      $('#addModelBtn').on('click', function() {
          $('#modelid').val('new').trigger('change');
      });

      $('#addVendorBtn').on('click', function() {
          $('#newvendorid').val('new').trigger('change');
      });

      $('#addMachineTypeBtn').on('click', function() {
          $('#machinetypeid').val('new').trigger('change');
      });

      $('#addFunctionalAccountBtn').on('click', function() {
          $('#newfunctionalaccountid').val('new').trigger('change');
      });

      $('#addBusinessUnitBtn').on('click', function() {
          $('#businessunitid').val('new').trigger('change');
      });

      // Handle Model dropdown - show/hide new model section
      $('#modelid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newModelSection').slideDown();
              $('#newmodelnumber').prop('required', true);
              $('#newvendorid').prop('required', true);
          } else {
              $('#newModelSection').slideUp();
              $('#newVendorSection').slideUp();
              $('#newmodelnumber').val('').prop('required', false);
              $('#newvendorid').val('').prop('required', false);
              $('#newmodelimage').val('');
              $('#newvendorname').val('').prop('required', false);
          }
      });

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

      // Handle Vendor dropdown within new model section
      $('#newvendorid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newVendorSection').slideDown();
              $('#newvendorname').prop('required', true);
          } else {
              $('#newVendorSection').slideUp();
              $('#newvendorname').val('').prop('required', false);
          }
      });

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

      // Handle Machine Type dropdown - show/hide new machine type section
      $('#machinetypeid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newMachineTypeSection').slideDown();
              $('#newmachinetypename').prop('required', true);
              $('#newfunctionalaccountid').prop('required', true);
          } else {
              $('#newMachineTypeSection').slideUp();
              $('#newFunctionalAccountSection').slideUp();
              $('#newmachinetypename').val('').prop('required', false);
              $('#newmachinetypedescription').val('');
              $('#newfunctionalaccountid').val('').prop('required', false);
              $('#newfunctionalaccountname').val('').prop('required', false);
          }
      });

      // Cancel new machine type
      $('#cancelNewMachineType').on('click', function() {
          $('#newMachineTypeSection').slideUp();
          $('#newFunctionalAccountSection').slideUp();
          $('#machinetypeid').val($('#machinetypeid option:first').val());
          $('#newmachinetypename').val('').prop('required', false);
          $('#newmachinetypedescription').val('');
          $('#newfunctionalaccountid').val('').prop('required', false);
          $('#newfunctionalaccountname').val('').prop('required', false);
      });

      // Handle Functional Account dropdown within new machine type section
      $('#newfunctionalaccountid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newFunctionalAccountSection').slideDown();
              $('#newfunctionalaccountname').prop('required', true);
          } else {
              $('#newFunctionalAccountSection').slideUp();
              $('#newfunctionalaccountname').val('').prop('required', false);
          }
      });

      // Cancel new functional account
      $('#cancelNewFunctionalAccount').on('click', function() {
          $('#newFunctionalAccountSection').slideUp();
          $('#newfunctionalaccountid').val('');
          $('#newfunctionalaccountname').val('').prop('required', false);
      });

      // Handle Business Unit dropdown - show/hide new business unit section
      $('#businessunitid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newBusinessUnitSection').slideDown();
              $('#newbusinessunitname').prop('required', true);
          } else {
              $('#newBusinessUnitSection').slideUp();
              $('#newbusinessunitname').val('').prop('required', false);
          }
      });

      // Cancel new business unit
      $('#cancelNewBusinessUnit').on('click', function() {
          $('#newBusinessUnitSection').slideUp();
          $('#businessunitid').val($('#businessunitid option:first').val());
          $('#newbusinessunitname').val('').prop('required', false);
      });

      // Form validation for edit form
      $('form[action*="editmacine.asp"]').on('submit', function(e) {
          // Validate new model section
          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 ($('#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;
                  }
              }
          }

          // Validate new machine type section
          if ($('#machinetypeid').val() === 'new') {
              if ($('#newmachinetypename').val().trim() === '') {
                  e.preventDefault();
                  alert('Please enter a machine type name or select an existing machine type');
                  $('#newmachinetypename').focus();
                  return false;
              }
              if ($('#newfunctionalaccountid').val() === '' || $('#newfunctionalaccountid').val() === 'new') {
                  if ($('#newfunctionalaccountid').val() === 'new') {
                      if ($('#newfunctionalaccountname').val().trim() === '') {
                          e.preventDefault();
                          alert('Please enter a functional account name or select an existing functional account');
                          $('#newfunctionalaccountname').focus();
                          return false;
                      }
                  } else {
                      e.preventDefault();
                      alert('Please select a functional account for the new machine type');
                      $('#newfunctionalaccountid').focus();
                      return false;
                  }
              }
          }

          // Validate new business unit section
          if ($('#businessunitid').val() === 'new') {
              if ($('#newbusinessunitname').val().trim() === '') {
                  e.preventDefault();
                  alert('Please enter a business unit name or select an existing business unit');
                  $('#newbusinessunitname').focus();
                  return false;
              }
          }
      });
  });
  </script>

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