document.addEventListener("DOMContentLoaded", async () => {

    //イベント登録
    Q("#search_button").addEventListener("click", () => {
        searchExec();
    });
    Q("#search_clear_button").addEventListener("click", () => {
        Q(".search_input_form").value = "";
    });

    Q("#search_input_form").addEventListener("keydown", (e) => {
        if (e.keyCode == 13) {
            e.preventDefault();
            searchExec();
        }
    });

    Q("#sort_type").addEventListener("change", (e) => {
        e.preventDefault();
        searchExec();
    });

    QA(".search_word").forEach(tag => {
        tag.addEventListener("click", function () {
            tag = this.getAttribute("data-search");
            location.href = `${BASE_URL}/search?q=${encodeURI(tag)}`;
        });
    });

    QA(".console_tag_cloud .tag").forEach(tag => {
        tag.addEventListener("click", () => {
            const tagText = tag.textContent.slice(1);
            window.location.href = `${BASE_URL}/search?q=%23${encodeURIComponent(tagText)}`;
        });
    });

    const moreLink = Q(".console_tag_cloud .tag_cloud_more_link");
    if (moreLink) {
        moreLink.addEventListener("click", () => {
            Q(".tag-cloud-more").classList.toggle("visible");
        });
    }

});

//検索実行
function searchExec() {
    if (Q('#search_input_form').value != "検索...") {
        location.href = `${BASE_URL}/search?q=` + encodeURIComponent(Q('#search_input_form').value) + '&sort_type=' + Q('#sort_type').value;
    }
}
