var prices_min_array = [
    {
        id: "0",
        value: "下限なし",
    },
    {
        id: "1",
        value: "2000",
    },
    {
        id: "2",
        value: "2500",
    },
    {
        id: "3",
        value: "3000",
    },
    {
        id: "4",
        value: "3500",
    },
    {
        id: "5",
        value: "4000",
    },
    {
        id: "6",
        value: "4500",
    },
    {
        id: "7",
        value: "5000",
    },
    {
        id: "8",
        value: "5500",
    },
    {
        id: "9",
        value: "6000",
    },
];
var prices_max_array = [
    {
        id: "0",
        value: "2500",
    },
    {
        id: "1",
        value: "3000",
    },
    {
        id: "2",
        value: "3500",
    },
    {
        id: "3",
        value: "4000",
    },
    {
        id: "4",
        value: "4500",
    },
    {
        id: "5",
        value: "5000",
    },
    {
        id: "6",
        value: "5500",
    },
    {
        id: "7",
        value: "6000",
    },
    {
        id: "8",
        value: "7000",
    },
    {
        id: "9",
        value: "上限なし",
    },
];

const redirectAffectUI = {
    FILTER: "filter",
    SEARCH: "search",
};

var total_page;
var current_page;
var records_per_page = 10;

$(function () {
    $(".total_items").html(
        "<img style='height: 18px;' src='/img/common/loading.gif' alt='...'/>"
    );
    $("#sp_extra_info_list").html(
        "<img style='height: 18px;' src='/img/common/loading.gif' alt='...'/>"
    );
    $("#extra_info_list").html(
        "<img style='height: 18px;' src='/img/common/loading.gif' alt='...'/>"
    );
    $(".conditional-search-info").html(
        "<img style='height: 18px;' src='/img/common/loading.gif' alt='...'/>"
    );

    $("#property-list .button > button").on({
        mouseover: function () {
            $(this).css("opacity", 0.7);
        },
        mouseout: function () {
            $(this).css("opacity", 1);
        },
    });

    page = getUrlParameter("p");
    page = parseInt(page == null ? 1 : page);
    if (no_land) {
        var dik = document.getElementById(
            "type_is_condominium_conditioned_land_sale"
        ).parentNode;
        dik.style.display = "none";

        document.getElementById(
            "is_condominium_conditioned_land_sale"
        ).style.display = "none";
    }
    // if not from property/index or F5 (refresh)
    if (
        !(document.referrer.includes("/property") || document.referrer === "")
    ) {
        localStorage.setItem("property-list-search", "");
    }

    const searchKeyword = localStorage.getItem("property-list-search");
    getPropertyList(
        area01,
        area02,
        price_min,
        price_max,
        searchKeyword || keyword,
        page,
        sort_by,
        no_land
    );

    loadRecentData();
    acordionListSearch();

    $("#select_sort_by").on("change", function () {
        $("#result_loading_bar").show();
        $(".tbl_content").hide();
        sort_by = $("#select_sort_by").val();
        updateFormTarget();
        $("#form_search").submit();
    });

    $(".nagoya_area_sel").on("click", function () {
        if (!check_area_data) {
            $(".area_loading").css(
                "background-image",
                "url('/img/common/loading.gif')"
            );
            $(".area_loading").css("background-position", "right center");
            $(".area_loading").css("background-repeat", "no-repeat");
            $(".area_loading").css("background-size", "18px 18px");
        }
    });

    $(".aichi_area_sel").on("click", function () {
        if (!check_area_data) {
            $(".area_loading").css(
                "background-image",
                "url('/img/common/loading.gif')"
            );
            $(".area_loading").css("background-position", "right center");
            $(".area_loading").css("background-repeat", "no-repeat");
            $(".area_loading").css("background-size", "18px 18px");
        }
    });

    const redirectBy = localStorage.getItem("property-list-redirect-from");

    if (redirectBy == redirectAffectUI.SEARCH) {
        // search by keyword
        const urlParams = new URLSearchParams(window.location.search);
        for (let p of urlParams) {
            if (p[0] == "keyword") {
                localStorage.setItem("property-list-search", p[1]);
                urlParams.set("keyword", p[1]);
            }
        }
        document.querySelector(".search-box").style.display = "grid";
        document.querySelector(".search-box input").value =
            localStorage.getItem("property-list-search") || searchKeyword;
        document.querySelector(".custom-box-sort").style.display = "none";
        document.querySelector(".search-box-text").style.display = "block";
        document.querySelector(".btn-wrap-custom").style.display = "none";

        history.pushState(null, null, `?${urlParams.toString()}`);
    } else {
        const btnFilters = document.querySelectorAll(".btn-wrap .btn-filter");
        btnFilters.forEach((btnFilter) => (btnFilter.style.display = "flex"));

        document.querySelector(".breadcrumb-option-item").style.display =
            "inline-block";
    }
});

function updateFormTarget() {
    var action = createActionParams();
    let params = new URLSearchParams(window.location.search);
    let initDataOnUrl = {};
    for (let p of params) {
        if (
            p[0] == "area02" ||
            p[0] == "category_lines" ||
            p[0] == "brand_category_ids"
        ) {
            initDataOnUrl[p[0]] = p[1].split(",");
        } else {
            initDataOnUrl[p[0]] = p[1];
        }
    }
    const dataKeys = Object.keys(initDataOnUrl);
    let paramsUrl = [];
    for (let i = 0; i < dataKeys.length; i++) {
        if (
            dataKeys[i] == "area02" ||
            dataKeys[i] == "category_lines" ||
            dataKeys[i] == "grand_shop_id" ||
            dataKeys[i] == "item_per_page" ||
            dataKeys[i] == "security_code" ||
            dataKeys[i] == "brand_id" ||
            dataKeys[i] == "brand_category_ids" ||
            dataKeys[i] == "price_min" ||
            dataKeys[i] == "price_max" ||
            dataKeys[i] == "site_area_min" ||
            dataKeys[i] == "site_area_max" ||
            dataKeys[i] == "floor_area_min" ||
            dataKeys[i] == "floor_area_max" ||
            dataKeys[i] == "theme_new" ||
            dataKeys[i] == "price_revision" ||
            dataKeys[i] == "ready_to_move_in" ||
            dataKeys[i] == "iot_house" ||
            dataKeys[i] == "keyword"
        ) {
            if (Array.isArray(initDataOnUrl[dataKeys[i]])) {
                if (initDataOnUrl[dataKeys[i]].length > 0) {
                    paramsUrl.push(
                        `${dataKeys[i]}=${initDataOnUrl[dataKeys[i]].join(",")}`
                    );
                }
            } else {
                if (dataKeys[i] === "keyword") {
                    // insert value after keyword=
                    const idx = action.indexOf("keyword");
                    if (idx > -1) {
                        action =
                            action.substring(0, idx + "keyword".length) +
                            `=${initDataOnUrl[dataKeys[i]]}` +
                            action.substring(idx + "keyword".length);
                    }
                } else if (initDataOnUrl[dataKeys[i]]) {
                    paramsUrl.push(
                        `${dataKeys[i]}=${initDataOnUrl[dataKeys[i]]}`
                    );
                }
            }
        }
    }
    if (action) {
        if (no_land == 1) {
            $("#form_search").attr(
                "action",
                "/property/list.php?" +
                    action +
                    "&no_land=1" +
                    `&${paramsUrl.join("&")}`
            );
        } else {
            $("#form_search").attr(
                "action",
                "/property/list.php?" + action + `&${paramsUrl.join("&")}`
            );
        }
    } else {
        if (no_land == 1) {
            $("#form_search").attr("action", "/property/list.php?no_land=1");
        } else {
            $("#form_search").attr("action", "/property/list.php");
        }
    }
}

function createActionParams() {
    var area01 = [],
        area02 = [],
        price_min,
        price_max;
    var action_area01 = "",
        action_area02 = "",
        action = "";
    //get keyword value
    if ($(".hasClone").length == 0)
        //PC
        var keyword_val = $(".keyword").val();
    //SP
    else var keyword_val = $(".hasClone .keyword").val();

    //get area value
    var nagoya_area_sel = $(".nagoya_area_sel").val();
    var aichi_area_sel = $(".aichi_area_sel").val();

    if (aichi_area_sel.indexOf("area_01") !== -1) {
        aichi_area01 = aichi_area_sel.substring(8);
        area01.push(aichi_area01);
        action_area01 += "area01=" + aichi_area01;
    }
    if (nagoya_area_sel.indexOf("area_01") !== -1) {
        nagoya_area01 = nagoya_area_sel.substring(8);
        area01.push(nagoya_area01);
        var check = "";
        if (action_area01) {
            check = ",";
        } else {
            check = "area01=";
        }
        action_area01 += check + nagoya_area01;
    }

    // if (aichi_area_sel.indexOf("area_02") !== -1) {
    //     aichi_area02 = aichi_area_sel.substring(8);
    //     area02.push(aichi_area02);
    //     action_area02 += "area02=" + aichi_area02;
    // }
    // if (nagoya_area_sel.indexOf("area_02") !== -1) {
    //     nagoya_area02 = nagoya_area_sel.substring(8);
    //     area02.push(nagoya_area02);
    //     var check = "";
    //     if (action_area02) {
    //         check = ",";
    //     } else {
    //         check = "area02=";
    //     }
    //     action_area02 += check + nagoya_area02;
    // }
    action += action_area01;
    var check = "";
    if (action_area01 && action_area02) {
        check = "&";
    }
    action += check + action_area02;

    //get price value
    price_min_val = $(".js_choose_price01").val();
    price_max_val = $(".js_choose_price02").val();
    if (price_min_val != 0) price_min = prices_min_array[price_min_val].value;
    if (price_max_val != 9) price_max = prices_max_array[price_max_val].value;

    if ($("#type_is_condominium_conditioned_land_sale").is(":checked")) {
        var is_condominium_conditioned_land_sale = 1;
    }
    if ($("#type_is_moveable").is(":checked")) {
        var is_moveable = 1;
    }
    if ($("#type_has_more_five_properties").is(":checked")) {
        var has_more_five_properties = 1;
    }

    if ($("#type_is_property_icn_train").is(":checked")) {
        var is_property_icn_train = 1;
    }

    if ($("#type_is_property_icn_car").is(":checked")) {
        var is_property_icn_car = 1;
    }

    if ($("#type_is_wooden_window").is(":checked")) {
        var is_wooden_window = 1;
    }

    if ($("#type_is_property_icn_wide").is(":checked")) {
        var is_property_icn_wide = 1;
    }

    if ($("#type_style_n").is(":checked")) {
        var is_type_style_n = 1;
    }

    if ($("#type_style_n_zeh").is(":checked")) {
        var is_type_style_n_zeh = 1;
    }

    if ($("#type_style_new_family").is(":checked")) {
        var is_type_style_new_family = 1;
    }

    if ($("#type_style_earth").is(":checked")) {
        var is_type_style_earth = 1;
    }

    if ($("#type_style_p").is(":checked")) {
        var is_type_style_p = 1;
    }
    if ($("#type_style_u").is(":checked")) {
        var is_type_style_u = 1;
    }
    if ($("#type_style_ugarage").is(":checked")) {
        var is_type_style_ugarage = 1;
    }
    if ($("#type_landsat").is(":checked")) {
        var is_type_landsat = 1;
    }
    // if ($('#type_windowwood').is(":checked")) {
    // 	var is_type_windowwood = 1;
    // }
    if ($("#type_style_other").is(":checked")) {
        var is_type_style_other = 1;
    }
    if ($("#type_wf_interior").is(":checked")) {
        var wf_interior = 1;
    }
    if ($("#type_price_revision").is(":checked")) {
        var price_revision = 1;
    }
    // if ($('#type_has_zeh').is(":checked")) {
    // var has_zeh = 1;
    // }

    if (price_min) {
        if (action) {
            check = "&";
        } else {
            check = "";
        }
        action += check + "pr_min=" + price_min;
    }
    if (price_max) {
        if (action) check = "&";
        else check = "";
        action += check + "pr_max=" + price_max;
    }

    //is_condominium_conditioned_land_sale
    if (is_condominium_conditioned_land_sale == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "is_condominium_conditioned_land_sale";
    }

    //is_moveable
    if (is_moveable == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "is_moveable";
    }

    //has_more_five_properties
    if (has_more_five_properties == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "has_more_five_properties";
    }

    //is_property_icn_train
    if (is_property_icn_train == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "is_property_icn_train";
    }

    //is_property_icn_car
    if (is_property_icn_car == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "is_property_icn_car";
    }

    //is_wooden_window
    if (is_wooden_window == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "is_wooden_window";
    }

    //is_property_icn_wide
    if (is_property_icn_wide == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "is_property_icn_wide";
    }

    var wf_style_ary = [];

    if (is_type_style_n == 1) {
        wf_style_ary.push(3);
    }
    if (is_type_style_p == 1) {
        wf_style_ary.push(2);
    }
    if (is_type_style_u == 1) {
        wf_style_ary.push(1);
    }
    if (is_type_style_ugarage == 1) {
        wf_style_ary.push(4);
    }
    if (is_type_landsat == 1) {
        wf_style_ary.push(5);
    }
    // if (is_type_windowwood == 1) {
    // 	wf_style_ary.push(6);
    // }
    if (is_type_style_other == 1) {
        wf_style_ary.push(0);
    }

    if (is_type_style_n_zeh == 1) {
        wf_style_ary.push(7);
    }

    if (is_type_style_new_family == 1) {
        wf_style_ary.push(8);
    }

    if (is_type_style_earth == 1) {
        wf_style_ary.push(9);
    }

    if (wf_style_ary.length > 0) {
        if (action) check = "&";
        else check = "";
        action += check + "wf_style=" + wf_style_ary.toString();
    }

    //has_zeh
    // if (has_zeh == 1) {
    // if (action)
    // check = "&";
    // else
    // check = "";
    // action += check + 'has_zeh';
    // }

    //wf_interior
    if (wf_interior == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "wf_interior";
    }

    //price_revision
    if (price_revision == 1) {
        if (action) check = "&";
        else check = "";
        action += check + "price_revision";
    }

    //sort by
    var sort_by = $("#select_sort_by").val();
    if (sort_by) {
        if (action) check = "&";
        else check = "";
        action += check + "sort_by=" + sort_by;
    }
    if (keyword_val) {
        if (action) check = "&";
        else check = "";
        action += check + "keyword";
    } else {
        $(".keyword").val("");
    }

    return action;
}

function getPropertyList(
    area01_str,
    area02_str,
    price_min,
    price_max,
    keyword,
    page,
    sort_by,
    no_land
) {
    current_page = page;

    var area01 = [],
        area02 = [];
    if (area01_str != "") area01 = area01_str.split(",");
    if (area02_str != "") area02 = area02_str.split(",");
    var area01_length = area01.length;
    var area02_length = area02.length;

    $("#is_condominium_conditioned_land_sale").hide();
    $("#is_moveable").hide();
    $("#has_more_five_properties").hide();
    $("#is_property_icn_train").hide();
    $("#is_property_icn_car").hide();
    $("#is_wooden_window").hide();
    $("#is_property_icn_wide").hide();

    $("#is_type_style_n").hide();
    $("#is_type_style_n_zeh").hide();
    $("#is_type_style_new_family").hide();
    $("#is_type_style_earth").hide();
    $("#is_type_style_p").hide();
    $("#is_type_style_u").hide();
    $("#is_type_style_ugarage").hide();
    $("#is_type_landsat").hide();
    // $("#is_type_windowwood").hide();
    $("#is_type_style_other").hide();

    // $("#has_zeh").hide();
    $("#wf_interior").hide();

    $("#price_revision").hide();

    $("#type_is_condominium_conditioned_land_sale").prop("checked", false);
    $("#type_is_moveable").prop("checked", false);
    $("#type_has_more_five_properties").prop("checked", false);

    $("#type_is_property_icn_train").prop("checked", false);

    $("#type_is_property_icn_car").prop("checked", false);

    $("#type_is_wooden_window").prop("checked", false);

    $("#type_is_property_icn_wide").prop("checked", false);

    $("#type_style_n").prop("checked", false);
    $("#type_style_p").prop("checked", false);
    $("#type_style_u").prop("checked", false);
    $("#type_style_n_zeh").prop("checked", false);
    $("#type_style_new_family").prop("checked", false);
    $("#type_style_earth").prop("checked", false);
    $("#type_style_ugarage").prop("checked", false);
    $("#type_landsat").prop("checked", false);
    // $("#type_windowwood").prop("checked", false);
    $("#type_style_other").prop("checked", false);
    $("#type_wf_interior").prop("checked", false);
    $("#type_price_revision").prop("checked", false);
    // $("#type_has_zeh").prop("checked", false);
    //set value of area to select box
    if (area01_length > 0) {
        for (i = 0; i < area01_length; i++) {
            if (
                area01[i] == 1 ||
                area01[i] == 2 ||
                area01[i] == 3 ||
                area01[i] == 4 ||
                area01[i] == 5
            ) {
                $(".nagoya_area_sel").val("area_01_" + area01[i]);
            } else {
                if (area01[i]) {
                    $(".aichi_area_sel").val("area_01_" + area01[i]);
                }
            }
        }
    }
    if (area02_length > 0) {
        for (j = 0; j < area02_length; j++) {
            if (
                area02[j] == 1 ||
                area02[j] == 2 ||
                area02[j] == 3 ||
                area02[j] == 4 ||
                area02[j] == 5 ||
                area02[j] == 6 ||
                area02[j] == 7 ||
                area02[j] == 8 ||
                area02[j] == 9 ||
                area02[j] == 10 ||
                area02[j] == 11 ||
                area02[j] == 12 ||
                area02[j] == 13 ||
                area02[j] == 14 ||
                area02[j] == 15 ||
                area02[j] == 16
            ) {
                $(".nagoya_area_sel").val("area_02_" + area02[j]);
            } else {
                if (area02[j]) {
                    $(".aichi_area_sel").val("area_02_" + area02[j]);
                }
            }
        }
    }

    //set value for price
    var price_min_set, price_max_set;

    if (price_min) {
        for (var i in prices_min_array) {
            if (prices_min_array[i].value == price_min) {
                price_min_set = prices_min_array[i].id;
            }
        }
    } else {
        price_min_set = 0;
    }
    if (price_max) {
        for (var i in prices_max_array) {
            if (prices_max_array[i].value == price_max) {
                price_max_set = prices_max_array[i].id;
            }
        }
    } else {
        price_max_set = 9;
    }
    $(".js_choose_price01").val(price_min_set);
    $(".js_choose_price02").val(price_max_set);

    if (keyword) {
        $(".keyword").val(keyword);
        $(".keyword_show").html(keyword);
    } else {
        $(".keyword_show").html("なし");
    }
    $("#select_sort_by").val(sort_by);
    let params = new URLSearchParams(window.location.search);
    let initDataOnUrl = {};
    for (let p of params) {
        if (
            p[0] == "area02" ||
            p[0] == "category_lines" ||
            p[0] == "brand_category_ids"
        ) {
            initDataOnUrl[p[0]] = p[1].split(",");
        } else {
            initDataOnUrl[p[0]] = p[1];
        }
    }
    var dataJson = {
        keyword: keyword,
        item_per_page: records_per_page,
        page_number: current_page,
        sort_by: sort_by,
        ...initDataOnUrl,
    };

    if (area01_length > 0) dataJson.area01 = area01;
    if (area02_length > 0) dataJson.area02 = area02;
    if (is_moveable) {
        dataJson.is_moveable = 1;
        $("#is_moveable").show();
        $("#type_is_moveable").prop("checked", true);
    }
    if (is_condominium_conditioned_land_sale) {
        dataJson.is_condominium_conditioned_land_sale = 1;
        $("#is_condominium_conditioned_land_sale").show();
        $("#type_is_condominium_conditioned_land_sale").prop("checked", true);
    }
    if (has_more_five_properties) {
        dataJson.has_more_five_properties = 1;
        $("#has_more_five_properties").show();
        $("#type_has_more_five_properties").prop("checked", true);
    }

    if (is_property_icn_train) {
        dataJson.is_property_icn_train = 1;
        $("#is_property_icn_train").show();
        $("#type_is_property_icn_train").prop("checked", true);
    }

    if (is_property_icn_car) {
        dataJson.is_property_icn_car = 1;
        $("#is_property_icn_car").show();
        $("#type_is_property_icn_car").prop("checked", true);
    }

    if (is_wooden_window) {
        dataJson.is_wooden_window = 1;
        $("#is_wooden_window").show();
        $("#type_is_wooden_window").prop("checked", true);
    }

    if (is_property_icn_wide) {
        dataJson.is_property_icn_wide = 1;
        $("#is_property_icn_wide").show();
        $("#type_is_property_icn_wide").prop("checked", true);
    }

    var wf_style_ary = [];

    // if (is_type_style_n) {
    // 	wf_style_ary.push(3);
    // 	$("#is_type_style_n").show();
    // 	$("#type_style_n").prop("checked", true);
    // }
    // if (is_type_style_p) {
    // 	wf_style_ary.push(2);
    // 	$("#is_type_style_p").show();
    // 	$("#type_style_p").prop("checked", true);
    // }
    // if (is_type_style_u) {
    // 	wf_style_ary.push(1);
    // 	$("#is_type_style_u").show();
    // 	$("#type_style_u").prop("checked", true);
    // }
    // if (is_type_style_other) {
    // 	wf_style_ary.push(0);
    // 	$("#is_type_style_other").show();
    // 	$("#type_style_other").prop("checked", true);
    // }
    if (wf_style) {
        if (wf_style.includes(0)) {
            $("#is_type_style_other").show();
            $("#type_style_other").prop("checked", true);
        }
        if (wf_style.includes(1)) {
            $("#is_type_style_u").show();
            $("#type_style_u").prop("checked", true);
        }
        if (wf_style.includes(2)) {
            $("#is_type_style_p").show();
            $("#type_style_p").prop("checked", true);
        }
        if (wf_style.includes(3)) {
            $("#is_type_style_n").show();
            $("#type_style_n").prop("checked", true);
        }
        if (wf_style.includes(4)) {
            $("#is_type_style_ugarage").show();
            $("#type_style_ugarage").prop("checked", true);
        }
        if (wf_style.includes(5)) {
            $("#is_type_landsat").show();
            $("#type_landsat").prop("checked", true);
        }
        // if (wf_style.includes(6)) {
        // 	$("#is_type_windowwood").show();
        // 	$("#type_windowwood").prop("checked", true);
        // }
        if (wf_style.includes(7)) {
            $("#is_type_style_n_zeh").show();
            $("#type_style_n_zeh").prop("checked", true);
        }
        if (wf_style.includes(8)) {
            $("#is_type_style_new_family").show();
            $("#type_style_new_family").prop("checked", true);
        }
        if (wf_style.includes(9)) {
            $("#is_type_style_earth").show();
            $("#type_style_earth").prop("checked", true);
        }
        dataJson.wf_style = wf_style;
    }

    // if (has_zeh) {
    // dataJson.has_zeh = 1;
    // $("#has_zeh").show();
    // $("#type_has_zeh").prop("checked", true);
    // }
    if (wf_interior) {
        dataJson.wf_interior = 1;
        $("#wf_interior").show();
        $("#type_wf_interior").prop("checked", true);
    }
    if (price_revision) {
        dataJson.price_revision = 1;
        $("#price_revision").show();
        $("#type_price_revision").prop("checked", true);
    }
    if (price_min) dataJson.price_min = price_min;
    if (price_max) dataJson.price_max = price_max;
    if (no_land) dataJson.no_land = no_land;
    projectSearchApi(dataJson);
}

function projectSearchApi(dataJson) {
    $("#result_loading_bar").show();
    $(".tbl_content").hide();
    localStorage.setItem("dataJson", JSON.stringify(dataJson));
    call_ws_sumikae(
        "project/search",
        "POST",
        dataJson,
        function (status, data) {
            if (status == 200) {
                // render for /property/list page
                $("#result_loading_bar").hide();
                $(".tbl_content").show();
                document.querySelector(".custom-new-project-num").innerText =
                    data?.data?.extra_info?.project_new_num ?? 0;
                document.querySelector(".custom-property-num").innerText =
                    data?.data?.extra_info?.property_num ?? 0;

                var total_items = 0;
                var projects = data?.data?.result;
                if (projects) {
                    total_items = data.data.total_items;
                    var projects_length = projects.length;
                    var project = "";

                    for (i = 0; i < projects_length; i++) {
                        infra_memo_items = "";
                        if (isMobile) {
                            //SP: priority 交通1→2→3→4
                            if (projects[i]["infra_memo"] != null) {
                                var infra_memo_arr =
                                    projects[i]["infra_memo"].split(
                                        /(?:\r\n|\r|\n)/g
                                    );
                                for (j = 0; j < infra_memo_arr.length; j++) {
                                    if (infra_memo_arr[j]) {
                                        infra_memo_items = replaceEOL(
                                            infra_memo_arr[j]
                                        );
                                        break;
                                    }
                                }
                            } else {
                                if (projects[i]["infra_memo2"] != null) {
                                    infra_memo_items = replaceEOL(
                                        projects[i]["infra_memo2"]
                                    );
                                }
                            }
                        } else {
                            //PC: show all of infra memo
                            if (projects[i]["infra_memo"] != null) {
                                var infra_memo_arr =
                                    projects[i]["infra_memo"].split(
                                        /(?:\r\n|\r|\n)/g
                                    );
                                for (j = 0; j < infra_memo_arr.length; j++) {
                                    if (infra_memo_arr[j]) {
                                        infra_memo_items += replaceEOL(
                                            infra_memo_arr[j]
                                        );
                                        if (j != infra_memo_arr.length - 1)
                                            infra_memo_items += "</br>";
                                    }
                                }
                            }
                            if (projects[i]["infra_memo2"] != null) {
                                if (infra_memo_items != "")
                                    infra_memo_items += "<br/>";
                                infra_memo_items += replaceEOL(
                                    projects[i]["infra_memo2"]
                                );
                            }
                        }
                        var arr_feature_type1 = projects[i].arr_feature[1];
                        var arr_feature_type3 = projects[i].arr_feature[3];

                        // if (!isLogged && projects[i]["wf_member"] != 1) {
                        project += `<tr class="tbl-content-item ${
                            !isLogged && projects[i]["wf_member"] == 1
                                ? "property-item-lock-wrap"
                                : ""
                        } ">
                            <td class="tbl_content__check custom-content-checkbox-item" id="proj_id_${
                                projects[i].project_id
                            }">
                                <label><input type="checkbox" value="" name="area"></label>
                                  <div class="list_content_title__text">
                                                    ${
                                                        !isLogged &&
                                                        projects[i][
                                                            "wf_member"
                                                        ] == 1
                                                            ? ` <a class="content-link">`
                                                            : `<a class="content-link" href="/property/project.php?proj_id=${projects[i].project_id}" target="_blank">`
                                                    }

                                                    ${
                                                        isLogged &&
                                                        projects[i][
                                                            "wf_member"
                                                        ] == 1
                                                            ? `<span class="custom-members-only-text">会員限定</span>`
                                                            : ""
                                                    }
                                                    <span class="project-name-item">
                                                    ${cutWoodFriendText(
                                                        projects[i].project_name
                                                    )}
                                                    </span>
                                                    </a>

                                                    <div class='status-wrap'>
                                                    ${
                                                        projects[i]
                                                            .is_new_icon == 1
                                                            ? "<em>NEW</em>"
                                                            : ""
                                                    }
                                                    ${(projects[i].themes ?? [])
                                                        .filter(
                                                            (item) =>
                                                                item != "NEW"
                                                        )
                                                        .map((theme) => {
                                                            return `<p class="label-1">
                                                                    ${theme}
                                                                </p>`;
                                                        })
                                                        .toString()
                                                        .replace(/,/g, "")}

                                                        <p class='favorite-star list_content_title__rank ${
                                                            fav_projs.includes(
                                                                projects[
                                                                    i
                                                                ].project_id.toString()
                                                            )
                                                                ? "active"
                                                                : ""
                                                        }' id="proj_${
                            projects[i].project_id
                        }">
                                                            <img src="/resource/img/star-uncheck.svg" alt="">
                                                            <img src="/resource/img/star-check.svg" alt="">
                                                            <span>お気に入り</span>
                                                        </p>
                                                    </div>
                                                </div>
                            </td>

                            <td class="custom-content-box-item" onClick="${
                                !isLogged && projects[i]["wf_member"] == 1
                                    ? ""
                                    : `window.open('/property/project.php?proj_id=${projects[i].project_id}', '_blank')`
                            }">
                                <div class="box_media" style="width:100%">
                                    <div class="box_media__pic custom-image-item-wrap">
                                        <span>
                                            <span>
                                                <a href="/property/project.php?proj_id=${
                                                    projects[i].project_id
                                                }" class="rollover" target="_blank">
                                                    <img src="${
                                                        projects[i].main_image
                                                    }" alt="" class="fluid_image">
                                                </a>
                                            </span>
                                        </span>
                                    </div>
                                        <div class="box_media__txt custom-media-txt">
                                            <div class="list_content_description">
                                                <div class="description_link">`;

                        if (projects[i].address) {
                            project += `<p class="custom-item-location"> <i class="fa fa-map-marker custom-bus-icon custom-location-item"></i>
                            <span>${projects[i].address}</span></p>`;
                        }

                        if (infra_memo_items) {
                            project += `<p class="custom-item-address"><i class="fa fa-train custom-bus-icon custom-location-item"></i>
                            <span>${infra_memo_items}</span></p>`;
                        }

                        if (
                            projects[i].MIN_PRICE != null &&
                            projects[i].MAX_PRICE != null
                        ) {
                            if (
                                projects[i].MIN_PRICE == projects[i].MAX_PRICE
                            ) {
                                project += `<p class="custom-yen-price-item"><i class="fa fa-jpy custom-bus-icon custom-location-item custom-price-icon"></i><em class="custom-price-space">${numberWithCommas(
                                    projects[i].MIN_PRICE
                                )}</em>万円</p>`;
                            } else {
                                project += `<p class="custom-yen-price-item"><i class="fa fa-jpy custom-bus-icon custom-location-item custom-price-icon"></i><em class="custom-price-space">${numberWithCommas(
                                    projects[i].MIN_PRICE
                                )}</em>万円～<em>${numberWithCommas(
                                    projects[i].MAX_PRICE
                                )}</em>万円</p>`;
                            }
                        } else {
                            project += `<p class="custom-yen-price-item"><i class="fa fa-jpy custom-bus-icon custom-location-item custom-price-icon"></i><span class="custom-price-space">未定</span></p>`;
                        }

                        project += `</div>
                            <p class="description_label">
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "30",
                                    arr_feature_type1
                                )}">駅徒歩5分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "11",
                                    arr_feature_type1
                                )}">駅徒歩15分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "12",
                                    arr_feature_type1
                                )}">複数路線利用可</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "14",
                                    arr_feature_type1
                                )}">小学校徒歩10分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "15",
                                    arr_feature_type1
                                )}">中学校徒歩10分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "16",
                                    arr_feature_type1
                                )}">保育園・幼稚園徒歩10分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "17",
                                    arr_feature_type1
                                )}">スーパー徒歩10分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "18",
                                    arr_feature_type1
                                )}">コンビニ徒歩5分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "34",
                                    arr_feature_type1
                                )}">病院徒歩10分以内</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "21",
                                    arr_feature_type1
                                )}">前面道路6.0m以上</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "20",
                                    arr_feature_type1
                                )}">南面道路</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "23",
                                    arr_feature_type1
                                )}">土地50坪以上</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "22",
                                    arr_feature_type1
                                )}">角地</span>
                                <span class="label ${checkFeaturesType1Off(
                                    "1",
                                    "24",
                                    arr_feature_type1
                                )}">3台駐車可</span>`;

                        if (arr_feature_type3) {
                            for (let j = 0; j < arr_feature_type3.length; j++) {
                                if (
                                    (arr_feature_type3[j].feature_id == "23" &&
                                        arr_feature_type3[j].feature_type ==
                                            "3") ||
                                    (arr_feature_type3[j].feature_id == "24" &&
                                        arr_feature_type3[j].feature_type ==
                                            "3") ||
                                    (arr_feature_type3[j].feature_id == "25" &&
                                        arr_feature_type3[j].feature_type ==
                                            "3")
                                ) {
                                    arr_feature_type3[j].feature_id = 23;
                                    arr_feature_type3[j].feature_type = 3;
                                }
                            }
                        }

                        project += `<span class="label ${checkFeaturesType1Off(
                            "3",
                            "23",
                            arr_feature_type3
                        )}">LDK16帖以上</span>
                            <span class="label ${checkFeaturesType1Off(
                                "3",
                                "36",
                                arr_feature_type3
                            )}">対面キッチン</span>
                            </p>
                            </div>
                            <p class="link_content custom-link-content">
                                <a href="/property/project.php?proj_id=${
                                    projects[i].project_id
                                }" class="rollover" target="_blank"><img src="/resource/img/chevron_right.svg" alt=""></a>
                            </p>
                            </div>

                            </div>`;

                        if (!isLogged && projects[i]["wf_member"] == 1) {
                            project += `<div class="lock-wf-member-1">
                                <div class="lock-content">
                                    <img src="/resource/img/lock-red.svg" alt="">
                                    <p class="lock-title">会員限定公開物件</p>
                                </div>
                                <div class="lock-bottom">

                                    <a href="/mypage/login.php" target="_blank">
                                        <button>
                                        <span class="btn-free-text">無料！</span>
                                        <span>新規会員登録/ログインはこちら</span>
                                        <img src="/resource/img/chevron-right.svg" alt="">
                                        </button>
                                    </a>
                                </div>
                            </div>`;
                        }

                        project += `</td>
                        </tr>`;
                    }
                    $(".tbl_content").html(project);

                    $(".js-clone__content").each(function () {
                        var elClone = $(this);
                        if ($(window).width() < 768) {
                            var cloneObject = elClone.closest(".box_media");
                            elClone.insertBefore(cloneObject);
                        }
                        if ($(window).width() >= 768) {
                            var cloneObject = elClone
                                .closest("td")
                                .find(".box_media__txt");
                            //cloneObject.empty();
                            cloneObject.prepend(elClone);
                        }
                    });

                    adjustImgSizeInItemList();

                    window.onresize = function (e) {
                        adjustImgSizeInItemList();
                    };

                    $(".tbl_content").show();

                    $(".list_bukken .box_media__pic img").on(
                        "load",
                        function () {
                            $(this).each(function () {
                                var photoWmax = 320;
                                var photoHmax = 240;
                                var photoW = $(this).width();
                                var photoH = $(this).height();
                                if (photoW > photoH) {
                                    if (photoW > photoWmax) {
                                        $(this).css("height", "auto");
                                        $(this).width(photoWmax + "px");
                                    }
                                    if (photoH > photoHmax) {
                                        $(this).css("width", "auto");
                                        $(this).height(photoHmax + "px");
                                    }
                                }
                                if (photoW < photoH) {
                                    if (photoH > photoHmax) {
                                        $(this).css("width", "auto");
                                        $(this).height(photoHmax + "px");
                                    }
                                    if (photoW > photoWmax) {
                                        $(this).css("height", "auto");
                                        $(this).width(photoWmax + "px");
                                    }
                                }
                                if (photoW == photoH) {
                                    if (photoW > photoWmax) {
                                        $(this).css("height", "auto");
                                        $(this).width(photoWmax + "px");
                                    }
                                }
                            });
                        }
                    );

                    //paginator
                    total_page = Math.ceil(
                        data.data.total_items / records_per_page
                    );
                    var action = createActionParams();
                    if (action) {
                        if (no_land) {
                            url = "/property/list.php?no_land=1&" + action;
                        } else {
                            url = "/property/list.php?" + action;
                        }

                        renderPaginator(
                            current_page,
                            total_page,
                            url + "&p=",
                            5,
                            ".lst_pagination"
                        );
                    } else {
                        if (no_land) {
                            url = "/property/list.php?no_land=1";
                        } else {
                            url = "/property/list.php";
                        }
                        renderPaginator(
                            current_page,
                            total_page,
                            url + "?p=",
                            5,
                            ".lst_pagination"
                        );
                    }
                    customCheck();
                    showLinkBottom();
                    initFavButtons();
                    initRequestAllButton();

                    var extra_info = "";
                    extra_info += '<div class="extra_info_content">';
                    if (data.data.extra_info.average_price)
                        extra_info +=
                            '<div class="extra-info-item"><p class="item-extra"><span class="extra-info-title">平均価格</span><span class="custom-acreage-text">' +
                            data.data.extra_info.average_price +
                            "万円</span></p>";
                    if (data.data.extra_info.min_price)
                        extra_info +=
                            '<p class="item-extra"><span class="extra-info-title">最低価格</span><a href="#" onclick="chooseProject(' +
                            data.data.extra_info.min_price_proj_id +
                            ')"><span class="custom-acreage-text">' +
                            data.data.extra_info.min_price +
                            "万円</span></a></p></div>";
                    if (data.data.extra_info.average_site_area)
                        extra_info +=
                            '<div class="extra-info-item"><p class="item-extra"><span class="extra-info-title">平均敷地面積</span><span class="custom-acreage-text"><span>' +
                            data.data.extra_info.average_site_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.average_site_area) +
                            "坪）</span></p>";
                    if (data.data.extra_info.max_site_area)
                        extra_info +=
                            '<p class="item-extra"><span class="extra-info-title">最大敷地面積</span><a href="#" onclick="chooseProject(' +
                            data.data.extra_info.max_site_area_proj_id +
                            ')"><span class="custom-acreage-text"><span>' +
                            data.data.extra_info.max_site_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.max_site_area) +
                            "坪）</span></a></p></div>";
                    if (data.data.extra_info.average_floor_area)
                        extra_info +=
                            '<div class="extra-info-item"><p class="item-extra"><span class="extra-info-title">平均延床面積</span><span class="custom-acreage-text"><span>' +
                            data.data.extra_info.average_floor_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.average_floor_area) +
                            "坪）</span></p>";
                    if (data.data.extra_info.max_floor_area)
                        extra_info +=
                            '<p class="item-extra"><span class="extra-info-title">最大延床面積</span><a href="#" onclick="chooseProject(' +
                            data.data.extra_info.max_floor_area_proj_id +
                            ')"><span><span class="custom-acreage-text">' +
                            data.data.extra_info.max_floor_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.max_floor_area) +
                            "坪）<span></a></p></div>";
                    extra_info += "</div>";

                    var sp_extra_info =
                        '<p style="font-weight:bold">うち、一戸建て（' +
                        data.data.extra_info.project_new_num +
                        "件｜" +
                        data.data.extra_info.property_num +
                        "戸）</p>";
                    sp_extra_info += '<span class="extra_info_content">';
                    if (data.data.extra_info.average_price)
                        sp_extra_info +=
                            "<span>平均価格：<span>" +
                            data.data.extra_info.average_price +
                            "</span>万円</span>";
                    if (data.data.extra_info.min_price)
                        sp_extra_info +=
                            '<span>最低価格：<a href="#" onclick="chooseProject(' +
                            data.data.extra_info.min_price_proj_id +
                            ')"><span>' +
                            data.data.extra_info.min_price +
                            "</span>万円</a></span>";
                    if (data.data.extra_info.average_site_area)
                        sp_extra_info +=
                            "<span>平均敷地面積：<span>" +
                            data.data.extra_info.average_site_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.average_site_area) +
                            "坪）</span>";
                    if (data.data.extra_info.average_floor_area)
                        sp_extra_info +=
                            "<span>平均延床面積：<span>" +
                            data.data.extra_info.average_floor_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.average_floor_area) +
                            "坪）</span>";
                    if (data.data.extra_info.max_site_area)
                        sp_extra_info +=
                            '<span>最大敷地面積：<a href="#" onclick="chooseProject(' +
                            data.data.extra_info.max_site_area_proj_id +
                            ')"><span>' +
                            data.data.extra_info.max_site_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.max_site_area) +
                            "坪）</a></span>";
                    if (data.data.extra_info.max_floor_area)
                        sp_extra_info +=
                            '<span>最大延床面積：<a href="#" onclick="chooseProject(' +
                            data.data.extra_info.max_floor_area_proj_id +
                            ')"><span>' +
                            data.data.extra_info.max_floor_area +
                            "</span>m<sup>2</sup>（" +
                            m2ToTsubo(data.data.extra_info.max_floor_area) +
                            "坪）</a></span>";
                    sp_extra_info += "</span>";
                    $("#extra_info_list").html(extra_info);
                    $("#extra_info_list").show();
                    $("#sp_extra_info_list").html(sp_extra_info);
                } else {
                    $(".tbl_content").html("");
                    $(".box_pagination .lst_pagination").html("");
                    $("#extra_info_list").hide();
                }
                const conditionalSearchTextInStorage =
                    localStorage.getItem("conditional-search-text") || "";

                $(".conditional-search-info").html(
                    conditionalSearchTextInStorage
                );

                $(".total_items").html(total_items);
                disable_price();
            }

            $("#result_loading_bar").hide();

            fGetAreaList();
        },
        function (error) {
            console.log("error", error);
            loadInitialSearchData();
            $("#result_loading_bar").hide();
            $(".tbl_content").show();
        }
    );
}

function acordionListSearch() {
    $(".js_search_title").click(function () {
        if (!$(this).hasClass("active")) {
            $(this).addClass("active");
            $(this).text("閉じる");
            $(this)
                .closest(".box_search")
                .find(".js_search_content")
                .slideDown(300)
                .addClass("is_opened");
            /*
			$(this).parents().find('.box-sort').hide();
			*/
        } else {
            $(this).removeClass("active");
            $(this).text("条件を変更");
            $(this)
                .closest(".box_search")
                .find(".js_search_content")
                .slideUp(300)
                .removeClass("is_opened");
            /*
			$(this).parents().find('.box-sort').hide();
			*/
        }
        //updateValueSelectSearch();
        $(".js_choose_price01").on("change", function () {
            disable_price();
        });
    });
    updateValueSelectSearch();
}

function updateValueSelectSearch() {
    var triggerUpdate = $(".js_search_content");
    (showPriceSlect01 = $(".js_select_price01")),
        (showPriceSlect02 = $(".js_select_price02"));

    showNagoyaSelect = $(".js_select_nagoya");
    showAichiSelect = $(".js_select_aichi");
    var valSelectAria,
        valSelectPrice01,
        valSelectPrice02,
        valSelectNagoyaArea,
        valSelectAichiArea;
    triggerUpdate.each(function () {
        valSelectPrice01 = $(this)
            .find(".js_choose_price01>option:selected")
            .text();
        valSelectPrice02 = $(this)
            .find(".js_choose_price02>option:selected")
            .text();
        if (valSelectPrice01.indexOf("下限なし（初期値）") !== -1)
            valSelectPrice01 = "下限なし";
        if (valSelectPrice02.indexOf("上限なし（初期値）") !== -1)
            valSelectPrice02 = "上限なし";
        showPriceSlect01.text(valSelectPrice01);
        showPriceSlect02.text(valSelectPrice02);

        valSelectNagoyaArea = $(this)
            .find(".nagoya_area_sel>optgroup>option:selected")
            .text()
            .split("(")[0];
        valSelectAichiArea = $(this)
            .find(".aichi_area_sel>optgroup>option:selected")
            .text()
            .split("(")[0];

        js_select_area = "";
        if (valSelectNagoyaArea) js_select_area += valSelectNagoyaArea;
        if (valSelectAichiArea) {
            if (js_select_area) js_select_area += "、" + valSelectAichiArea;
            else js_select_area += valSelectAichiArea;
        }
        if (js_select_area) $(".js_area_selected").html(js_select_area);
        else $(".js_area_selected").html("なし");
    });
}

function disable_price() {
    $(".opt_price02").removeAttr("disabled");
    var price01 = $(".js_choose_price01").val();
    var price02 = $(".js_choose_price02").val();

    if (parseInt(price02) + 2 < price01) {
        $(".js_choose_price02").val(9);
    }
    for (i = 1; i < price01; i++) {
        $(".opt_price02_" + (i - 2)).attr("disabled", "disabled");
    }
}

var check_area_data = false;

function fGetAreaList() {
    var dataJson = {};
    call_ws_sumikae("area", "GET", dataJson, function (status, data) {
        if (status == 200) {
            for (i = 0; i < data.data.length; i++) {
                $(".count_area_01_" + data.data[i].id).append(
                    "(" + data.data[i].count + ")"
                );
                if (data.data[i].count == 0)
                    $(".count_area_01_" + data.data[i].id).attr(
                        "disabled",
                        "disabled"
                    );

                for (j = 0; j < data.data[i].area_02.length; j++) {
                    $(".count_area_02_" + data.data[i].area_02[j].id).append(
                        "(" + data.data[i].area_02[j].count + ")"
                    );
                    if (data.data[i].area_02[j].count == 0)
                        $(".count_area_02_" + data.data[i].area_02[j].id).attr(
                            "disabled",
                            "disabled"
                        );
                }
            }
            check_area_data = true;
        }
        $(".area_loading").css("background-image", "none");
    });
}

function chooseProject(proj_id) {
    location.href = "/property/project.php?proj_id=" + proj_id;
    return false;
}
let dataJsonTmp;
let conditionalSearchText;
function revertSearchModal() {
    if (
        JSON.stringify(dataJsonTmp) ==
        JSON.stringify(localStorage.getItem("dataJson"))
    ) {
        return;
    }
    localStorage.setItem("dataJson", dataJsonTmp);
    localStorage.setItem("conditional-search-text", conditionalSearchText);
    $(".conditional-search-info").html(conditionalSearchText);
    dataJson = { brand_id: 1, grand_shop_id: 2, item_per_page: 10 };
    dataStorage = JSON.parse(localStorage.getItem("dataJson") || "{}");
    categoryFilter = dataStorage.category_lines || [];
    areaFilter = dataStorage.area02 || [];
    bandCategoryIds = dataStorage.brand_category_ids || [];
    propertyBrands = dataStorage.brand_category_ids || [];
    countTimeInitLoad = 0;
    loadPropertyLine();
    loadPropertyArea();
}

const searchBtns = document.querySelectorAll(".btn-wrap .btn-filter");
const modalContainer = document.querySelector(".modal-container");
const modalWrap = document.querySelector(".modal-wrap");
searchBtns.forEach((searchBtn) => {
    searchBtn.onclick = function () {
        modalContainer.onclick = (event) => {
            const withinBoundaries = event.composedPath().includes(modalWrap);
            // click outside
            if (
                !withinBoundaries &&
                modalContainer.className.includes("active")
            ) {
                modalContainer.classList.remove("active");
                revertSearchModal();
            }
        };
        dataJsonTmp = localStorage.getItem("dataJson");
        conditionalSearchText =
            localStorage.getItem("conditional-search-text") || "";
        modalContainer.classList.add("active");
    };
});

const closeModalBtn = document.querySelector(".close-modal");
closeModalBtn.onclick = function () {
    modalContainer.classList.remove("active");
    revertSearchModal();
};

$(document).ready(function () {
    const clearSearchBtn = document.querySelector(".clear-search");
    clearSearchBtn.onclick = function () {
        areaFilter = [];
        categoryFilter = [];
        propertyBrands = [];
        const selectList = document.querySelectorAll(".standard_select");
        selectList.forEach((selectBox) => (selectBox.selectedIndex = 0));
        const checkboxList = modalContainer.querySelectorAll(
            'input[type="checkbox"]'
        );

        checkboxList.forEach((checkboxEl) => (checkboxEl.checked = false));
        localStorage.setItem("dataJson", "{}");
        getPropertyCount({}, true);
    };

    const executeSearch = document.querySelector(".execute-search");
    // override search click event in property search
    executeSearch.onclick = function () {
        const dataJson = JSON.parse(localStorage.getItem("dataJson"));
        const dataKeys = Object.keys(dataJson);
        let paramsUrl = [];
        for (let i = 0; i < dataKeys.length; i++) {
            if (Array.isArray(dataJson[dataKeys[i]])) {
                if (dataJson[dataKeys[i]].length > 0) {
                    paramsUrl.push(
                        `${dataKeys[i]}=${dataJson[dataKeys[i]].join(",")}`
                    );
                }
            } else {
                if (dataJson[dataKeys[i]]) {
                    if (dataKeys[i] === "p") {
                        paramsUrl.push("p=1");
                    } else {
                        paramsUrl.push(
                            `${dataKeys[i]}=${dataJson[dataKeys[i]]}`
                        );
                    }
                }
            }
        }
        if (window.location.href.includes("list.php")) {
            history.pushState(null, null, `?${paramsUrl.join("&")}`);
        }

        // after reload, initial function (which have projectSearchApi()) will be called.
        window.scroll({
            top: 0,
            behavior: "auto",
        });
        location.reload();
    };

    const searchIconBtn = document.querySelector(".search-icon");
    const inputEl = document.querySelector(".search-box input");
    searchIconBtn.onclick = () => {
        const dataJson = JSON.parse(localStorage.getItem("dataJson"));
        localStorage.setItem("property-list-search", inputEl.value);

        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        urlParams.set("p", 1);
        urlParams.set("keyword", inputEl.value);
        history.pushState(null, null, `?${urlParams.toString()}`);
        current_page = 1;
        projectSearchApi({
            ...dataJson,
            sort_by: sort_by || 0,
            keyword: inputEl.value,
        });
    };

    inputEl.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            e.preventDefault();
            searchIconBtn.click();
        }
    });

    document.querySelector(".close-register-modal").onclick = () => {
        handleCloseModal();
    };

    //close modal when click outside
    document.addEventListener("click", (e) => {
        if (e.target.className.includes("outer-modal")) {
            handleCloseModal();
        }
    });

    //close custom modal
    function handleCloseModal() {
        $("#outer-modal").removeClass("opened");
        document.body.style = "overflow:visible;max-height:100vh";
    }
});
