$(document).ready(function(){let vocabulariesPortletId="com_liferay_asset_categories_admin_web_portlet_AssetCategoriesAdminPortlet";const setPermission=()=>{setTimeout(()=>{$("[id*\x3d'_inputPermissionsViewRole']").each(function(){this.selectedIndex=0})},1E3)};function getComponent(label,value){const typeRequest=getTypeRequest();if(typeRequest===vocabulariesPortletId)return`\n        \x3cdiv class\x3d"mb-2"\x3e\n          \x3cspan class\x3d"mr-1"\x3e${label}:\x3c/span\x3e\n          \x3cspan class\x3d"text-secondary"\x3e${value}\x3c/span\x3e\n        \x3c/div\x3e\n      `;
return`\n      \x3cdiv class"d-flex flex-column mb-3"\x3e\n        \x3cp class\x3d"sidebar-dt"\x3e${label.toUpperCase()}\x3c/p\x3e\n        \x3cp class\x3d"sidebar-dd"\x3e${value}\x3c/p\x3e\n      \x3c/div\x3e\n    `}function getVocabularyAndCategoryFromUrl(path){const reExp=/(?:group\/.*\/~\/control_panel\/manage\/-\/categories_admin\/vocabulary\/([^\/?]*)(?:\/category\/([^\??]*))?)/;const match=reExp.exec(window.location.pathname);if(!match)return[null,null];return[match[1],match[2]]}function getTypeRequest(){const queryString=
window.location.search;const path=window.location.pathname;const urlParams=new URLSearchParams(queryString);const typeRequest=urlParams.get("p_p_id");if(typeRequest)return typeRequest;const [vocabulary,category]=getVocabularyAndCategoryFromUrl(path)||[null,null];if(vocabulary||category)return vocabulariesPortletId}function addIdToPage(){const queryString=window.location.search;const urlParams=new URLSearchParams(queryString);const typeRequest=getTypeRequest();switch(typeRequest){case "com_liferay_journal_web_portlet_JournalPortlet":selector=
"#_com_liferay_journal_web_portlet_JournalPortlet_infoPanelId .info-panel-content .sidebar-body";value=urlParams.get("_com_liferay_journal_web_portlet_JournalPortlet_folderId");label="ID da pasta";break;case "com_liferay_document_library_web_portlet_DLAdminPortlet":selector="#_com_liferay_document_library_web_portlet_DLAdminPortlet_infoPanelId .info-panel-content .sidebar-body";value=urlParams.get("_com_liferay_document_library_web_portlet_DLAdminPortlet_folderId");label="ID da pasta";break;case vocabulariesPortletId:selector=
"#portlet_com_liferay_asset_categories_admin_web_portlet_AssetCategoriesAdminPortlet .portlet-content-container .portlet-body .container-fluid.container-fluid-max-xl.container-view .row .col-lg-9 .sheet.sheet-full .mb-5:first";let [vocabulary,category]=getVocabularyAndCategoryFromUrl()||[null,null];value=category||vocabulary;label=`ID ${category?"da categoria":"do vocabul\u00e1rio"}`;break;case "com_liferay_users_admin_web_portlet_UsersAdminPortlet":selector="#_com_liferay_users_admin_web_portlet_UsersAdminPortlet_fm .sheet .sheet-header";
value=urlParams.get("_com_liferay_users_admin_web_portlet_UsersAdminPortlet_organizationId");label="ID da Organiza\u00e7\u00e3o";break;default:return}if(selector&&value)$(selector).append(getComponent(label,value))}if(Liferay.ThemeDisplay.getUserName()==null)return;addIdToPage();setPermission();Liferay.on("endNavigate",function(event){Liferay.on("allPortletsReady",function(event){addIdToPage();setPermission()})})});
Liferay.on("allPortletsReady", function () {
  let frame;
  let shouldRun = true;

  setTimeout(() => {
    setInterval(() => {
      frame = window.document.querySelector(".cldf-observatorio-cidadao-theme .observatorio-cidadao-iframe-portlet iframe");
      if (frame == null) {
        return shouldRun = true;
      }
      else if (shouldRun) {
        setTimeout(() => {
          run();
          $(frame).parents(".observatorio-cidadao-iframe-portlet").removeClass("d-none");
        }, 1500);
        return shouldRun = false;
      }
    }, 1000);
  }, 1000);

  function run() {
    const modal = '<div class="modal observatorio-cidadao-submit-modal fade" id="observatorio-cidadao-submit-modal" tabindex="-1" aria-labelledby="observatorio-cidadao-submit-modal" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><h6>Sua sugestão foi enviada com sucesso!</h6></div><div class="modal-footer"><button type="button" class="btn btn-white border rounded-circle w-100" data-dismiss="modal">Voltar</button></div></div></div></div>'
    const frameBody = frame.contentDocument.body;
    const id = $(frame).parents(".portlet-boundary_com_liferay_nested_portlets_web_portlet_NestedPortletsPortlet_").attr("id");
    const hash = window.location.hash.split("=")[0];
    const submitButton = $(frameBody).find("#ddm-form-submit");
    const formBody = $(frameBody).find(".lfr-ddm-form-page");
    const form = $(frameBody).find("form.form");

    if (!frameBody) {
      shouldRun = true;
      return;
    }

    frameBody.classList.add("cldf-observatorio-iframe-body");

    setTimeout(() => {
      AUI().use('cookie', function (Y) {
        let darkMode = Y.Cookie.get("dark-mode-on");
        if (darkMode) {
          $(form).addClass("dark-mode");
        } else {
          $(form).removeClass("dark-mode");
        }
      });
    }, 1000);

    // ESTILO DO BOTÃO E DISPARO DA MODAL
    $(submitButton).text("Enviar");
    $(submitButton).addClass("disabled");
    $(submitButton).attr("data-toggle", "modal");
    $(submitButton).attr("data-target", "#observatorio-cidadao-submit-modal");
    $("body").append(modal);

    if (hash == `#${id}`) {
      $("#observatorio-cidadao-submit-modal").modal("show");
    }

    $(form).on("submit", function (e) {
      setTimeout(() => {
        $(frame).hide();
        window.location.href = window.location.pathname + `#${id}`;
        window.location.reload();
      }, 500)
    })

    // ACERTAR TAMANHO DOS INPUTS
    const inputs = $(frameBody).find(".col-md-6");

    for (let i = 0; i < inputs.length; i++) {
      $(inputs[i]).removeClass("col-md-6").addClass("col-sm-6")
    }

    // VALIDAR CAMPOS
    const nameInput = $(formBody).find("label:contains('Nome')").siblings().first();
    let validName;

    if ($(nameInput).val()?.length > 0) {
      validName = true;
    } else {
      validName = false;
    }

    $(nameInput).on("input", function () {
      if ($(nameInput).val()?.length > 0) {
        validName = true;
      } else {
        validName = false;
      }
      validateButton();
    })

    const phoneInput = $(formBody).find("label:contains('Telefone')").siblings().first();
    let validPhone;

    if ($(phoneInput).val()?.length > 0) {
      validPhone = true;
    } else {
      validPhone = false;
    }

    $(phoneInput).on("input", function () {
      if ($(phoneInput).val()?.length > 0) {
        validPhone = true;
      } else {
        validPhone = false;
      }
      validateButton();
    })

    const emailInput = $(formBody).find("label:contains('E-mail')").siblings().first();
    let validEmail;

    if ($(emailInput).val()?.length > 0) {
      validEmail = true;
    } else {
      validEmail = false;
    }

    $(emailInput).on("input", function () {
      if ($(emailInput).val()?.length > 0) {
        validEmail = true;
      } else {
        validEmail = false;
      }
      validateButton();
    })

    const typeDropdown = $(frameBody).find(".dropdown-menu");
    const typeSelect = $(formBody).find("label:contains('Tipo de manifestação')").siblings().first()?.val();
    let validSelect;

    if ($(typeSelect).length > 0) {
      validSelect = true;
    } else {
      validSelect = false;
    }

    $(typeDropdown).on("click", function (e) {
      let typeValue = $(e.target).text();
      if (typeValue == "Escolha uma Opção") {
        validSelect = false;
      } else {
        validSelect = true;
      }
    })

    const manifestInput = $(formBody).find("label:contains('Manifestação')").siblings().first();
    let validManifest;

    if ($(manifestInput).val()?.length > 0) {
      validManifest = true;
    } else {
      validManifest = false;
    }

    $(manifestInput).on("input", function () {
      if ($(manifestInput).val()?.length > 0) {
        validManifest = true;
      } else {
        validManifest = false;
      }
      validateButton();
    })

    const validateButton = () => {
      if (validName && validPhone && validEmail && validManifest && validSelect) {
        $(submitButton).removeClass("disabled");
      } else {
        $(submitButton).addClass("disabled");
      }
    }

    validateButton();
  }
});
