let apply_link = {}
let gravity_form = {}

function openTab(event, tabId) {
  let i, tabSection, tabButtons

  tabSection = document.getElementsByClassName("rentpress-tab-section")
  for (i = 0; i < tabSection.length; i++) {
    tabSection[i].style.display = "none"
  }

  tabButtons = document.getElementsByClassName("rentpress-tab-button")
  for (i = 0; i < tabButtons.length; i++) {
    tabButtons[i].className = tabButtons[i].className.replace(
      " rentpress-is-active",
      ""
    )
  }

  document.getElementById(tabId).style.display = "block"
  event.currentTarget.classList.add("rentpress-is-active")

  setTimeout(function () {
    const expandButton = document.getElementById("rentpress-expand-all")
    if (expandButton.classList.contains("rentpress-expanded")) {
      const accordions = document.getElementsByClassName("rentpress-accordion")
      for (let i = 0; i < accordions.length; i++) {
        accordions[i].classList.add("rentpress-open")
        const openPanel = accordions[i].nextElementSibling
        openPanel.style.maxHeight = openPanel.scrollHeight + "px"
      }
    }
  }, 50)
}

function openDefaultTab() {
  const tabButtons = document.getElementsByClassName("rentpress-tab-button")
  if (typeof tabButtons[0] != "undefined") {
    tabButtons[0].click()
  }
}

function toggleAccordion() {
  const accordion = document.getElementsByClassName("rentpress-accordion")
  for (let i = 0; i < accordion.length; i++) {
    accordion[i].addEventListener("click", function () {
      this.classList.toggle("rentpress-open")
      const panel = this.nextElementSibling
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null
      }
      openAccordionPanels()
    })
  }
}

function expandAll() {
  this.classList.toggle("rentpress-expanded")
  const accordions = document.getElementsByClassName("rentpress-accordion")
  for (let i = 0; i < accordions.length; i++) {
    const panel = accordions[i].nextElementSibling
    if (this.classList.contains("rentpress-expanded")) {
      this.innerHTML = "Close All"
      accordions[i].classList.add("rentpress-open")
      panel.style.maxHeight = panel.scrollHeight + "px"
    } else {
      this.innerHTML = "Expand All"
      accordions[i].classList.remove("rentpress-open")
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null
      }
    }
  }
}

function setUpExpandAll() {
  const expandButton = document.getElementById("rentpress-expand-all")
  if (typeof expandButton != "undefined" && expandButton != null) {
    expandButton.addEventListener("click", expandAll)
  }
}

function openAccordionPanels(event) {
  const openAccordions = document.getElementsByClassName("rentpress-open")
  for (let i = 0; i < openAccordions.length; i++) {
    const openPanel = openAccordions[i].nextElementSibling
    if (openPanel.style.maxHeight == 0) {
      openPanel.style.maxHeight = "none"
    }
  }
}

function toggleOverrides() {
  const overrideBoxes =
    this.parentElement.parentElement.parentElement.getElementsByClassName(
      "rentpress-override"
    )
  for (let i = 0; i < overrideBoxes.length; i++) {
    if (this.checked == true) {
      overrideBoxes[i].checked = true
    } else {
      overrideBoxes[i].checked = false
    }
  }
}

function setUpOverrideAll(event) {
  const selectAll = document.getElementsByClassName("rentpress-override-all")
  for (let i = 0; i < selectAll.length; i++) {
    selectAll[i].addEventListener("change", toggleOverrides)
  }
}

function overrideFields() {
  const overrideCheckboxes =
    document.getElementsByClassName("rentpress-override")
  for (let i = 0; i < overrideCheckboxes.length; i++) {
    if (overrideCheckboxes[i].classList.contains("rentpress-override-all")) {
      continue
    }
    const overrideCheckboxName = overrideCheckboxes[i].getAttribute("name")
    const inputName = overrideCheckboxName.substring(
      0,
      overrideCheckboxName.length - 9
    )
    const input = document.getElementById(inputName)
    if (overrideCheckboxes[i].checked == true) {
      input.disabled = false
    } else {
      input.disabled = true
    }
  }
}

function overrideRangeFields() {
  const overrideCheckboxName = this.getAttribute("name")
  const maxInputOverrideName = overrideCheckboxName.replace("min", "max")
  const maxOverride = document.getElementsByName(maxInputOverrideName)[0]
  maxOverride.click()
}

function setUpOverrides(event) {
  const overrideCheckboxes =
    document.getElementsByClassName("rentpress-override")
  const overrideRangeCheckboxes = document.getElementsByClassName(
    "rentpress-override-range"
  )
  for (let i = 0; i < overrideCheckboxes.length; i++) {
    overrideCheckboxes[i].addEventListener("change", overrideFields)
  }
  for (let i = 0; i < overrideRangeCheckboxes.length; i++) {
    overrideRangeCheckboxes[i].addEventListener("change", overrideRangeFields)
  }
}

function openEditUnitModal(unit) {
  const modalPadding =
    window.innerHeight * 0.1 + "px " + window.innerWidth * 0.1 + "px"
  document.getElementById("rentpress-edit-unit-form-container").style.display =
    "block"
  document.getElementById("rentpress-edit-unit-form-container").style.padding =
    modalPadding
  document.body.style.overflow = "hidden"

  const unitElements = document.getElementsByClassName(
    "rentpress-edit-unit-form-value"
  )
  for (let index = 0; index < unitElements.length; index++) {
    let editUnitValueKey = unitElements[index].name.replace("_edit", "")
    if (editUnitValueKey == "unit_ready_date") {
      let d = new Date(unit[editUnitValueKey])
      unitElements[index].value = d.toISOString().split("T")[0]
    } else {
      unitElements[index].value = unit[editUnitValueKey]
    }
  }
}

function closeEditUnitModal() {
  const modal = document.getElementById("rentpress-edit-unit-form-container")

  // Add fade-out class
  modal.classList.add("fade-out")

  // After animation finishes, hide the modal
  modal.addEventListener("animationend", function handler() {
    modal.style.display = "none"
    modal.classList.remove("fade-out") // reset for next open
    document.body.style.overflow = "auto"
    hideDeleteConfirmation()
    modal.removeEventListener("animationend", handler)
  })
}

function clearRequestResults() {
  setTimeout(function () {
    const requestResults = document.getElementsByClassName(
      "rentpress-request-results"
    )
    for (let i = 0; i < requestResults.length; i++) {
      requestResults[i].innerHTML = ""
    }
  }, 3000)
}

function showDeleteConfirmation() {
  document.getElementById(
    "rentpress-delete-confirmation-container"
  ).style.display = "block"
  document.getElementById(
    "rentpress-edit-unit-button-container"
  ).style.display = "none"
}

function hideDeleteConfirmation() {
  document.getElementById(
    "rentpress-edit-unit-button-container"
  ).style.display = "block"
  document.getElementById(
    "rentpress-delete-confirmation-container"
  ).style.display = "none"
}

function filterPropertySelector() {
  const input = document.getElementById("rentpress-property-selector-search")
  const filter = input.value.toUpperCase()
  const properties = document.getElementsByClassName(
    "rentpress-prop-selector-title"
  )

  for (let i = 0; i < properties.length; i++) {
    const propertyTitle = properties[i].innerText
    const selectorRow = properties[i].parentElement
    if (propertyTitle.toUpperCase().indexOf(filter) > -1) {
      selectorRow.style.display = "inherit"
    } else {
      selectorRow.style.display = "none"
    }
  }
}

window.addEventListener("load", function () {
  openDefaultTab()
  toggleAccordion()
  setUpOverrideAll()
  setUpOverrides()
  setUpExpandAll()

  let neighborhoodPropertySearchInput = document.getElementById(
    "rentpress-property-selector-search"
  )
  if (neighborhoodPropertySearchInput) {
    neighborhoodPropertySearchInput.addEventListener("keyup", function () {
      filterPropertySelector()
    })
  }
})

window.addEventListener("resize", function () {
  openAccordionPanels()
})

jQuery(document).ready(function ($) {
  $("#rentpress_custom_field_property_office_hours_checkbox").change(
    function () {
      if ($(this).is(":checked")) {
        $(".rentpress-office-hours").each(function () {
          $(this).prop("disabled", false)
        })
      } else {
        $(".rentpress-office-hours").each(function () {
          $(this).prop("disabled", true)
        })
      }
    }
  )

  function refreshAddedUnits() {
    let unitParentFloorplanCode = $(
      "input[name='unit_parent_floorplan_code']"
    ).val()
    const data = {
      action: "rentpress_refresh_added_units_action",
      unit_parent_floorplan_code: unitParentFloorplanCode,
    }
    jQuery.post(ajaxurl, data, function (response) {
      $("#rentpress-unit-display").html(response)
    })
    return false
  }
  refreshAddedUnits()

  function addUnit() {
    var data = {
      action: "rentpress_create_unit_action",
    }
    $(".rentpress-new-unit-form-value").each((_, unit_data_element) => {
      if (unit_data_element.name !== "unit_rent_best") {
        data[unit_data_element.name] = unit_data_element.value
      }
      if (unit_data_element.name == "unit_ready_date") {
        if (Date.parse(unit_data_element.value) <= Date.parse(new Date())) {
          data["unit_available"] = 1
        } else {
          data["unit_available"] = null
        }
      }
      if (
        (unit_data_element.name === "unit_rent_min" ||
          unit_data_element.name === "unit_rent_max" ||
          unit_data_element.name === "unit_rent_base" ||
          unit_data_element.name === "unit_rent_market" ||
          unit_data_element.name === "unit_rent_effective") &&
        (unit_data_element.value < data["unit_rent_best"] ||
          !data["unit_edit_rent_best"]) &&
        unit_data_element.value
      ) {
        data["unit_rent_best"] = unit_data_element.value
      }
    })

    if (data["unit_rent_type_selection"]) {
      switch (data["unit_rent_type_selection"]) {
        case "Best Price":
          data["unit_rent_type_selection_cost"] = data["unit_rent_best"]
          break

        case "Market Rent":
          data["unit_rent_type_selection_cost"] = data["unit_rent_market"]
          break

        case "Base Rent":
          data["unit_rent_type_selection_cost"] = data["unit_rent_base"]
          break

        case "Effective Rent":
          data["unit_rent_type_selection_cost"] = data["unit_rent_effective"]
          break

        case "Minimum - Maximum":
          data["unit_rent_type_selection_cost"] = data["unit_rent_min"]
          break
      }
    }

    // Unit Input Validations
    // clear error message
    $("#results_for_new_unit").html("")
    // if unit code is not unique or is empty, display error text and don't submit
    if (
      $("#rentpress-unit-code").hasClass("rentpress-unit-error") ||
      $("#rentpress-unit-code").val() == ""
    ) {
      $("#results_for_new_unit").html(
        "<span class='rentpress-error'>The Unit Code must be unique</span>"
      )
      return
    }
    // if unit name is empty, display error text and don't submit
    if ($("#rentpress-unit-name").val() == "") {
      $("#results_for_new_unit").html(
        "<span class='rentpress-error'>The Unit Name must exist</span>"
      )
      return
    }
    // if unit date is empty, display error text and don't submit
    if ($("#rentpress-unit-ready-date").val() == "") {
      $("#results_for_new_unit").html(
        "<span class='rentpress-error'>There must be an available date</span>"
      )
      return
    }

    jQuery.post(ajaxurl, data, function (response) {
      if (response == 0) {
        $("#results_for_new_unit").html(
          "<span class='rentpress-error'>There was an error trying to add new unit</span>"
        )
      } else {
        $("#results_for_new_unit").html(
          "<span class='rentpress-success'>New unit successfully added</span>"
        )
        $("input[name='unit_code']").val("")
        refreshAddedUnits()
      }
      clearRequestResults()
    })
  }

  function editUnit() {
    var data = {
      action: "rentpress_edit_unit_action",
    }
    $(".rentpress-edit-unit-form-value").each((_, unit_data_element) => {
      if (unit_data_element.name !== "unit_edit_rent_best") {
        data[unit_data_element.name] = unit_data_element.value
      }
      if (unit_data_element.name == "unit_edit_ready_date") {
        if (Date.parse(unit_data_element.value) <= Date.parse(new Date())) {
          data["unit_edit_available"] = 1
        } else {
          data["unit_edit_available"] = null
        }
      }
      if (
        (unit_data_element.name === "unit_edit_rent_min" ||
          unit_data_element.name === "unit_edit_rent_max" ||
          unit_data_element.name === "unit_edit_rent_base" ||
          unit_data_element.name === "unit_edit_rent_market" ||
          unit_data_element.name === "unit_edit_rent_effective") &&
        (unit_data_element.value < data["unit_edit_rent_best"] ||
          !data["unit_edit_rent_best"]) &&
        unit_data_element.value
      ) {
        data["unit_edit_rent_best"] = unit_data_element.value
      }
    })

    if (data["unit_edit_rent_type_selection"]) {
      switch (data["unit_edit_rent_type_selection"]) {
        case "Best Price":
          data["unit_edit_rent_type_selection_cost"] =
            data["unit_edit_rent_best"]
          break

        case "Market Rent":
          data["unit_rent_type_selection_cost"] = data["unit_edit_rent_market"]
          break

        case "Base Rent":
          data["unit_edit_rent_type_selection_cost"] =
            data["unit_edit_rent_base"]
          break

        case "Effective Rent":
          data["unit_edit_rent_type_selection_cost"] =
            data["unit_edit_rent_effective"]
          break

        case "Minimum - Maximum":
          data["unit_edit_rent_type_selection_cost"] =
            data["unit_edit_rent_min"]
          break
      }
    }

    // Unit Input Validations
    // clear error message
    $("#results_for_edit_unit").html("")
    // if unit code is empty, display error text and don't submit
    if ($("#rentpress-edit-unit-code").val() == "") {
      $("#results_for_edit_unit").html(
        "<span class='rentpress-error'>The Unit Code must exist</span>"
      )
      return
    }
    // if unit name is empty, display error text and don't submit
    if ($("#rentpress-edit-unit-name").val() == "") {
      $("#results_for_edit_unit").html(
        "<span class='rentpress-error'>The Unit Name must exist</span>"
      )
      return
    }
    // if unit date is empty, display error text and don't submit
    if ($("#rentpress-edit-unit-ready-date").val() == "") {
      $("#results_for_edit_unit").html(
        "<span class='rentpress-error'>There must be an available date</span>"
      )
      return
    }

    jQuery.post(ajaxurl, data, function (response) {
      if (response == 0) {
        $("#results_for_edit_unit").html(
          "<span class='rentpress-error'>There was an error trying to edit a unit</span>"
        )
      } else {
        setTimeout(function () {
          $("#results_for_edit_unit").html(
            "<span class='rentpress-success'>Unit successfully edited</span>"
          )
        }, 150)
        $("input[name='unit_code']").val("")
        refreshAddedUnits()
        setTimeout(function () {
          closeEditUnitModal()
        }, 1000)
      }
      clearRequestResults()
    })
  }

  function deleteUnit() {
    var unitCode = $("#rentpress-edit-unit-code").val()
    var data = {
      action: "rentpress_delete_unit_action",
      unit_code: unitCode,
    }

    jQuery.post(ajaxurl, data, function (response) {
      if (response == 0) {
        $("#results_for_edit_unit").html(
          "<span class='rentpress-error'>There was an error trying to delete unit</span>"
        )
        clearRequestResults()
      } else {
        refreshAddedUnits()
        closeEditUnitModal()
      }
    })
    return false
  }

  $("#rentpress-new-unit-button").click(function (e) {
    e.preventDefault()
    addUnit()
  })

  $("#rentpress-save-unit-button").click(function (e) {
    e.preventDefault()
    editUnit()
  })

  $("#rentpress-permanent-delete-unit-button").click(function (e) {
    e.preventDefault()
    deleteUnit()
  })
})

/*
 *
 * Property Post Meta JS
 *
 */

/*
 *
 * Sync Options JS
 *
 */

// Sync Options JS
jQuery(document).ready(function ($) {
  let propertyCodes = []
  let syncIndex = 0
  const syncLimit = 10
  let manualSyncIndex = 0
  let manualPropertyCount = 0
  let isManualSyncing = false

  function rentpress_startFullPropertyDataResync() {
    $("#rentpress-resync-loading-image").css("display", "flex")
    $("#results-for-sync-topline-call").html(
      "<span style='color: #0f1d4a;'>Your property feed data request is starting.</span>"
    )
    $("#results-for-marketing-sync").html("")
    $("#results-for-template-changes").html("")
    syncIndex = 0
    propertyCodes = []

    var data = {
      action: "rentpress_getAllRemoteData",
    }

    jQuery
      .post(ajaxurl, data, function (response) {
        $("#results-for-sync-topline-call").html(response)
      })
      .then(function (response) {
        if (response["error"]) {
          $("#results-for-sync-topline-call").html(response["message"])
          $("#rentpress-resync-loading-image").css("display", "none")
          console.log(response["errorMessage"])
          return response
        }

        if (response["synced"]) {
          $("#results-for-sync-topline-call").html(
            "<span style='color: #0f1d4a;'>Success! Your property feed data has been synced</span>"
          )
        } else {
          $("#results-for-sync-topline-call").html(
            "<span style='color: #0f1d4a;'>Your property feed data is up to date</span>"
          )
        }
        propertyCodes = response["propertyCodes"]
        rentpress_runMarketingRefreshOnPropertyCodes().then(function () {
          // $("#rentpress-resync-loading-image").css("display", "none");
        })
      })
      .fail(function (response) {
        console.log(response)
        if (response.status === 500) {
          $("#results-for-sync-topline-call").html(
            "It appears there is an internal server error with your site. Check your WordPress debug.log or console. If problem persists, contact 30 Lines for assistance"
          )
        }
        $("#rentpress-resync-loading-image").css("display", "none")
      })
  }

  function rentpress_runMarketingRefreshOnPropertyCodes() {
    if (propertyCodes.length === 0) {
      $("#results-for-marketing-sync").html("No Properties to Sync")
      return
    }

    if (syncIndex >= propertyCodes.length) {
      const loader = $("#rentpress-resync-loading-image")
      loader.addClass("fade-out")
      loader.one("animationend", function () {
        loader.css("display", "none").removeClass("fade-out")
        $("#results-for-marketing-sync").html(
          "<span style='color: #0f1d4a;'>Syncing property post meta: Finished!</span>"
        )
        rentpress_runManualPropertySync()
      })
      return
    }

    let currentPropertyNumber = syncIndex + 1
    let currentCodes = propertyCodes.slice(syncIndex, syncIndex + syncLimit)
    $("#results-for-marketing-sync").html(
      "<span style='color: #0f1d4a;'>Syncing property post meta: " +
        currentPropertyNumber +
        " of " +
        propertyCodes.length +
        "</span>"
    )
    var data = {
      action: "rentpress_getAllMarketingDataForProperties",
      propertyCodes: currentCodes,
    }

    return jQuery
      .post(ajaxurl, data, function () {})
      .then(function () {
        syncIndex += syncLimit
        rentpress_runMarketingRefreshOnPropertyCodes()
      })
  }

  function rentpress_runManualPropertySync() {
    if (!isManualSyncing) {
      $("#results-for-manual-sync").html(
        "<span style='color: #0f1d4a;'>Begin manual property data refresh</span>"
      )
      isManualSyncing = true
    }

    function processBatch() {
      return jQuery
        .post(ajaxurl, {
          action: "rentpress_saveManualPropertyDataToDB",
          propertyCodes: propertyCodes,
          limit: syncLimit,
          offset: manualSyncIndex,
          manualPropertyCount: manualPropertyCount,
        })
        .then(function (response) {
          if (!response) {
            console.error("Empty response from manual property sync.")
            $("#results-for-manual-sync").html(
              "<span class='rentpress-error'>No response received during manual sync</span>"
            )
            isManualSyncing = false
            return
          }

          // Always update property count from PHP if provided
          if (response["manual_property_count"] !== undefined) {
            manualPropertyCount = response["manual_property_count"]
          }

          if (response["error"]) {
            console.log(response["errorMessage"])
            $("#results-for-manual-sync").html(
              "<span class='rentpress-error'>" +
                (response["message"] ||
                  "An error occurred during manual sync") +
                "</span>"
            )
            isManualSyncing = false
            return
          }

          if (!response["finished_sync"]) {
            let currentPropertyNumber = manualSyncIndex + 1
            $("#results-for-manual-sync").html(
              "<span style='color: #0f1d4a;'>Saving manual properties: " +
                currentPropertyNumber +
                " of " +
                manualPropertyCount +
                "</span>"
            )

            manualSyncIndex += syncLimit
            return processBatch()
          } else {
            $("#results-for-manual-sync").html(
              "<span style='color: #0f1d4a;'>" +
                (response["message"] || "Finished Manual Data Refresh") +
                "</span>"
            )
            isManualSyncing = false
          }
        })
    }

    processBatch()
  }

  $("#rentpress-marketing-resync-button").click(function () {
    rentpress_startFullPropertyDataResync()
  })

  // $("#rentpress-pricing-resync-button").click(function () {
  //   $("#rentpress-resync-loading-image").css("display", "block");
  //   $("#results_for_sync").html("");

  //   var data = {
  //     action: "rentpress_getAllPricingDataForProperties",
  //   };

  //   // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
  //   jQuery
  //     .post(ajaxurl, data, function (response) {
  //       $("#results_for_sync").html(response);
  //     })
  //     .fail(function (response) {
  //       console.log(response);
  //       if (response.status === 500) {
  //         $("#results_for_sync").html(
  //           "It appears there is an issue communicating with the server, please try again later. If problem persists contact 30 Lines for assistance"
  //         );
  //       }
  //     })
  //     .always(function () {
  //       $("#rentpress-resync-loading-image").css("display", "none");
  //     });
  // });

  $("#rentpress-theme-template-create").click(function () {
    $("#results-for-sync-topline-call").html("")
    $("#results-for-marketing-sync").html("")
    $("#results-for-template-changes").html("")
    var data = {
      action: "rentpress_createThemeTemplateFile",
    }

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    if (
      confirm(
        "This action will add files to your currently active theme for your chosen posts and pages. Any customizations will be overwritten."
      )
    ) {
      jQuery.post(ajaxurl, data, function (response) {
        console.log(response)
        if (response.includes("Success")) {
          $("#results-for-template-changes").html(
            "<span style='color: #0f1d4a;'>Success! RentPress Templates have been added to your active theme.</span>"
          )
        } else {
          $("#results-for-template-changes").html(
            "Error! RentPress Templates could not be added to your theme. If this error persists, contact 30 lines for assistance."
          )
        }
      })
    }
  })

  // check the url to see if it should set the tab
  const url = new URL(window.location.href)
  const lastTab = getParams(document.referrer)["settingstab"]
  const urlGet = url.searchParams.get("settingstab")
    ? url.searchParams.get("settingstab")
    : "Appearance"
  const urlTab = lastTab ? lastTab : urlGet

  const btn = document.getElementById("rentpress-marketing-resync-section")
  const apiFields = document.querySelectorAll(
    "#rentpress-api-credentials-settings-section input"
  )
  const submit_btn = document.querySelector(".resync-options-container #submit")

  if (apiFields.length) {
    for (let i = apiFields.length - 1; i >= 0; i--) {
      const field = apiFields[i]
      const args2 = { apiFields: apiFields, btn: btn }
      field.addEventListener("change", resyncFieldListener.bind(args2))
    }
  }

  if (submit_btn) {
    let allFields = [
      ...document.querySelectorAll(".rentpress-settings-wrapper input"),
      ...document.querySelectorAll(".rentpress-settings-wrapper select"),
    ]
    for (let i = allFields.length - 1; i >= 0; i--) {
      const field = allFields[i]
      field.addEventListener("change", adminFieldsListener)

      if (field.type == "checkbox" || field.type == "radio") {
        field.dataset.startval = field.checked
        continue
      } else {
        field.dataset.startval = field.value
      }
    }
    if (submit_btn.classList.value.includes("rentpress-options-submit")) {
      submit_btn.style.display = "none"
    }
  }
  changeSettingsTab(urlTab)
})

function makeOptionsPageConfig() {
  // this function is used to collect the diffrent fields and tabs to categorize them for use in the tab switcher
  let optionsPageDisplayConfig = {}
  const tabsListEl = document.getElementById("rentpress-tabs-menu-list")
  let tabListHtml = []
  // find all settings sections
  if (tabsListEl) {
    const sections = document.getElementsByClassName(
      "rentpress-settings-wrapper"
    )
    for (let i = sections.length - 1; i >= 0; i--) {
      const section = sections[i]
      let page = ""
      let fieldIds = []
      // make sure they have a tab to be added to
      if (typeof section.dataset.page != "undefined") {
        page = section.dataset.page
        // add the page to the sidebars menu
        tabListHtml.push(
          '<li id="rentpress-' +
            page.replace(/\s/g, "-").toLowerCase() +
            '-option" class="rentpress-tabs-menu-item" onclick="changeSettingsTab(`' +
            page +
            '`)"><h2><span>' +
            page +
            "</a></h2></li>"
        )
        // make the tabs field array if it doesn't exist
        if (typeof optionsPageDisplayConfig[page] == "undefined") {
          optionsPageDisplayConfig[page] = []
        }
        // add field to the tab array
        optionsPageDisplayConfig[page].push(section.id)
      }
    }
    // create the list items in the menus sidebar
    tabsListEl.innerHTML = [...new Set(tabListHtml)].join("")
    // send the list of tabs and fields
    return optionsPageDisplayConfig
  }
  return ""
}

function changeSettingsTab(tab) {
  // change active tab in the url
  const refresh =
    window.location.protocol +
    "//" +
    window.location.host +
    window.location.pathname +
    "?page=rentpress&settingstab=" +
    tab

  const optionsPageDisplayConfig = makeOptionsPageConfig()

  const selectedSections = optionsPageDisplayConfig[tab]
  // find all settings sections
  const sections = document.getElementsByClassName("rentpress-settings-wrapper")
  for (let i = sections.length - 1; i >= 0; i--) {
    const section = sections[i]
    if (section != null) {
      // hide all of the fields to be set to block later
      section.style.display = "none"
    }
  }

  if (typeof selectedSections != "undefined" ? selectedSections.length : "") {
    for (let j = selectedSections.length - 1; j >= 0; j--) {
      const selectedSection = document.getElementById(selectedSections[j])
      if (selectedSection != null) {
        // set the fields in this tab to block
        selectedSection.style.display = "block"
      }
    }
  }

  // remove active class from all buttons
  const tabBtn = document.getElementsByClassName("rentpress-tabs-menu-item")
  for (let i = tabBtn.length - 1; i >= 0; i--) {
    const btn = tabBtn[i]
    btn.classList.remove("rentpress-active-settings-tab-item")
  }
  // add active class to the tab that was clicked
  const activeTab = document.getElementById(
    "rentpress-" + tab.replace(/\s/g, "-").toLowerCase() + "-option"
  )
  if (activeTab) {
    activeTab.classList.add("rentpress-active-settings-tab-item")
    window.history.pushState({ path: refresh }, "", refresh)
  }
}

function getParams(url) {
  // get the params from a url string
  const params = {}
  const parser = document.createElement("a")
  parser.href = url
  const query = parser.search.substring(1)
  const vars = query.split("&")
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split("=")
    params[pair[0]] = decodeURIComponent(pair[1])
  }
  return params
}

function adminFieldsListener(event) {
  const submit = document.querySelector(".resync-options-container #submit")
  const blacklist_add_field = document.getElementById(
    "rentpress_amenity_blacklist_section_field"
  )
  const blacklist_remove_field = document.getElementById(
    "rentpress_amenity_blacklist_section_remove"
  )
  let allFields = [
    ...document.querySelectorAll(".rentpress-settings-wrapper input"),
    ...document.querySelectorAll(".rentpress-settings-wrapper select"),
  ]
  if (blacklist_remove_field != null) {
    allFields.push(blacklist_remove_field)
  }
  if (blacklist_add_field != null) {
    allFields.push(blacklist_add_field)
  }

  let change = false
  for (let i = allFields.length - 1; i >= 0; i--) {
    const el = allFields[i]
    if (el.type == "checkbox" || el.type == "radio") {
      if (el.checked != (el.dataset.startval === "true")) {
        change = true
      }
    } else {
      if (el.value != el.dataset.startval) {
        change = true
      }
    }
  }
  if (change) {
    submit.style.display = "block"
  } else {
    submit.style.display = "none"
  }
}

window.onload = function () {
  const checkboxes = getTemplateCheckBoxes()
  for (let i = checkboxes.length - 1; i >= 0; i--) {
    const checkbox = checkboxes[i]
    checkbox.addEventListener("click", checkTemplateValues)
  }
  checkTemplateValues()
}

function checkTemplateValues() {
  const checkboxes = getTemplateCheckBoxes()
  const btn = document.getElementById("rentpress-theme-template-create")
  let checked = false
  for (let i = checkboxes.length - 1; i >= 0; i--) {
    if (checkboxes[i].checked) {
      checked = true
    }
  }
  if (checked) {
    btn.style.display = "block"
  } else {
    btn.style.display = "none"
  }
}

function getTemplateCheckBoxes() {
  return [
    document.querySelector(
      "input#rentpress_post_templates_property_archive_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_property_single_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_floorplan_archive_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_floorplan_single_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_amenity_single_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_city_single_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_city_archive_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_property_taxonomy_single_section"
    ),
    document.querySelector(
      "input#rentpress_post_templates_property_type_single_section"
    ),
    document.querySelector("input#rentpress_post_templates_pet_single_section"),
    document.querySelector(
      "input#rentpress_post_templates_feature_single_section"
    ),
  ]
}

jQuery(document).ready(function ($) {
  let custom_uploader
  const click_elem = $(".rentpress-image-uploader-field")

  click_elem.click(function (e) {
    e.preventDefault()

    const target = document.getElementById(
      e.currentTarget.dataset.target + "-field"
    )
    const previewContainer = document.getElementById(
      e.currentTarget.dataset.target + "-upload-preview-container"
    )
    const limit = e.currentTarget.dataset.limit ?? true

    // If the uploader object has already been created, reopen it
    if (custom_uploader) {
      custom_uploader.open()
      return
    }

    // Create wp.media frame
    custom_uploader = wp.media.frames.file_frame = wp.media({
      title: "Choose Image",
      button: { text: "Choose Image" },
      multiple: limit == "false",
    })

    // When images are selected
    custom_uploader.on("select", function () {
      const selection = custom_uploader.state().get("selection")

      if (limit == "false") {
        // Multiple images
        let images = []
        let imageHTML = '<div class="rentpress-gallery-upload-previews-grid">'

        selection.map(function (attachment) {
          attachment = attachment.toJSON()
          images.push(attachment)

          // Safely get medium URL, fallback to original
          const imageUrl = attachment.sizes?.thumbnail?.url

          imageHTML +=
            "<div class='rentpress-gallery-single-image-wrapper' style='width:100px;'>" +
            "<span onclick='rentpressRemoveGalleryImage(" +
            attachment.id +
            ", `" +
            e.currentTarget.dataset.target +
            "`, this)'>X</span>" +
            "<img src='" +
            imageUrl +
            "'>" +
            "</div>"
        })

        imageHTML += "</div>"
        previewContainer.innerHTML = imageHTML
        target.value = JSON.stringify(images)
      } else {
        // Single image
        const attachment = selection.first().toJSON()
        const imageUrl = attachment.sizes?.thumbnail?.url

        previewContainer.innerHTML =
          '<img id="' +
          e.currentTarget.dataset.target +
          '-image" class="rentpress-image-upload-preview" src="' +
          imageUrl +
          '">'
        target.value = attachment.url
      }
    })

    custom_uploader.open()
  })
})

function rentpressClearPropertyGallery(event) {
  const parent = event.parentElement
  const image_container = document.getElementById(
    parent.getElementsByClassName("rentpress-image-uploader-field")[0].dataset
      .target + "-upload-preview-container"
  )
  parent.querySelector("input").value = ""
  image_container.innerHTML = ""
}

function rentpressRemoveGalleryImage(id, target, event) {
  if (!document.getElementById(target + "-field")?.value) return

  let fieldValueObj
  try {
    fieldValueObj = JSON.parse(
      document.getElementById(target + "-field")?.value ?? "[]"
    )
  } catch (e) {
    console.error("Failed to parse gallery field JSON:", e)
    return
  }

  const updatedImages = fieldValueObj.filter((element) => element?.id != id)
  document.getElementById(target + "-field").value =
    JSON.stringify(updatedImages)

  event?.parentElement?.style?.setProperty("display", "none")
}

function submitForm() {
  document.getElementById("main-rentpress-settings").submit()
}

function resyncFieldListener(event) {
  if (
    this.apiFields[0].value === this.apiFields[0].dataset.startval &&
    this.apiFields[1].value === this.apiFields[1].dataset.startval
  ) {
    this.btn.style.display = "block"
  } else {
    this.btn.style.display = "none"
  }
}

function ApplySettingsEventListener(value) {
  let fieldValue = this.value
  if (value && typeof value === "string") {
    fieldValue = value
  }
  switch (fieldValue) {
    case "1":
      apply_link.style.color = "#AAA"
      apply_link.style.opacity = "0.65"
      document.getElementById(
        "rentpress_custom_field_property_specific_contact_link"
      ).readOnly = true
      gravity_form.style.color = "#AAA"
      gravity_form.style.opacity = "0.65"
      document.getElementById(
        "rentpress_custom_field_property_specific_gravity_form"
      ).readOnly = true
      break
    case "2":
      apply_link.style.color = "unset"
      apply_link.style.opacity = "1"
      document.getElementById(
        "rentpress_custom_field_property_specific_contact_link"
      ).readOnly = false
      gravity_form.style.color = "#AAA"
      gravity_form.style.opacity = "0.65"
      document.getElementById(
        "rentpress_custom_field_property_specific_gravity_form"
      ).readOnly = true
      break
    case "3":
      apply_link.style.color = "#AAA"
      apply_link.style.opacity = "0.65"
      document.getElementById(
        "rentpress_custom_field_property_specific_contact_link"
      ).readOnly = true
      gravity_form.style.color = "unset"
      gravity_form.style.opacity = "1"
      document.getElementById(
        "rentpress_custom_field_property_specific_gravity_form"
      ).readOnly = false
      break
  }
}

function officeHoursEventListener() {
  const appendCheckbox = document.getElementsByClassName(
    "rentpress-office-hours-append-checkbox"
  )
  const overrideCheckbox = document.getElementsByClassName(
    "rentpress-office-override-day-checkbox"
  )
  const statusCheckbox = document.getElementsByClassName(
    "rentpress-office-hours-status"
  )

  for (let i = statusCheckbox.length - 1; i >= 0; i--) {
    statusCheckbox[i].addEventListener("change", function () {
      const baseField = this.parentNode.dataset.baseField
      const appendCheckbox = document.getElementById(baseField + "_append")

      if (this.value) {
        document.getElementById(baseField + "_open").parentNode.style.display =
          "none"
        document.getElementById(baseField + "_close").parentNode.style.display =
          "none"
      } else {
        document.getElementById(baseField + "_open").parentNode.style.display =
          "flex"
        document.getElementById(baseField + "_close").parentNode.style.display =
          "flex"
      }

      if (this.value === "replace" || appendCheckbox.checked) {
        document.getElementById(
          baseField + "_append_text"
        ).parentNode.style.display = "flex"
        document.getElementById(
          baseField + "_append"
        ).parentNode.style.display = "none"
      } else {
        document.getElementById(
          baseField + "_append_text"
        ).parentNode.style.display = "none"
        document.getElementById(
          baseField + "_append"
        ).parentNode.style.display = "flex"
      }
    })
  }

  for (let i = overrideCheckbox.length - 1; i >= 0; i--) {
    overrideCheckbox[i].addEventListener("click", function () {
      const fieldTypes = ["open", "close", "status"]
      for (let j = fieldTypes.length - 1; j >= 0; j--) {
        document.getElementById(
          this.dataset.baseField + "_" + fieldTypes[j]
        ).disabled = !this.checked
      }
    })
  }

  for (let i = appendCheckbox.length - 1; i >= 0; i--) {
    appendCheckbox[i].addEventListener("click", function () {
      const baseField = this.dataset.baseField
      const statusSelector = document.getElementById(
        baseField + "_status"
      ).value

      if (statusSelector.value === "replace" || this.checked) {
        document.getElementById(
          baseField + "_append_text"
        ).parentNode.style.display = "flex"
      } else {
        document.getElementById(
          baseField + "_append_text"
        ).parentNode.style.display = "none"
      }
    })
  }
}

window.onload = function () {
  const fields = document.getElementsByClassName("rentpress-shadow-field")
  const applyType = document.getElementById(
    "rentpress_custom_field_property_contact_type"
  )
  apply_link = document.getElementById(
    "rentpress_custom_field_property_specific_contact_link_group"
  )
  gravity_form = document.getElementById(
    "rentpress_custom_field_property_specific_gravity_form_group"
  )
  const amenities_blacklist = document.getElementById(
    "amenity-blacklist-filter-submit"
  )
  const add_to_blacklist = document.getElementById(
    "amenity-add-to-blacklist-submit"
  )

  for (let i = fields.length - 1; i >= 0; i--) {
    let field = fields[i]
    field.addEventListener("change", function () {
      if (this.getAttribute("data-start-value") != this.value) {
        document.getElementById(this.getAttribute("data-base-field")).value =
          this.value
      }
    })
  }

  if (amenities_blacklist) {
    amenities_blacklist.addEventListener("click", doAmenitiesBlacklistSearch)
  }

  if (add_to_blacklist) {
    add_to_blacklist.addEventListener("click", addAmenitiesToBlacklist)
  }

  if (applyType) {
    applyType.addEventListener("change", ApplySettingsEventListener)
    ApplySettingsEventListener(applyType.value)
  }

  const amenityBlacklist = document.getElementById("amenity-blacklist-wrapper")
  if (amenityBlacklist != null) {
    doAmenitiesBlacklistSearch()
  }
  officeHoursEventListener()
}
