$(function () {

  //すべてクリア後のページ内遷移対応（スマホのみ）
  if($(window).width() <= 820){
    let thisReferrer = document.referrer;
    let thisUrl = window.location.href;
    let ogUrl = $('meta[property="og:url"]').attr('content');
    //console.log('thisReferrer:', thisReferrer);
    //console.log('thisUrl:', thisUrl);
    //console.log('ogUrl:', ogUrl);

    if(thisUrl.indexOf('__search__') !== -1){
      //thisUrl = thisUrl.replace('__search__', '#search');
      ogUrl = ogUrl.replace('__search__', '');
      $('meta[property="og:url"]').attr('content', ogUrl);
      let arr = thisUrl.split('/');
      let str = arr[arr.length - 1];
      str = str.replace('__search__', '');
      //console.log('str:', str);
      window.history.replaceState('', '', str);
      //location.href = '#search';
      let pos = $('#search_area').offset().top;
      //console.log('pos:', pos);
      $('html,body').animate({scrollTop : pos}, 80, 'swing');
    }
  }

  //セレクトボックス
  var selectkinds ="";
    $('[data-selectbox]').on("click",function(){
      var clickselectkinds = $(this).attr("data-selectbox");
      if(selectkinds === clickselectkinds){
        $('[data-mockselect="'+clickselectkinds+'"]').slideToggle(100);
      } else {
        $('[data-mockselect]').hide();
        $('[data-mockselect="'+clickselectkinds+'"]').slideDown(100);
      }
      selectkinds = clickselectkinds;
    })
    $('[data-vl]').on("click",function(){
      var datavalue = $(this).attr('data-vl');
      var datatext = $(this).text();
      $('[data-txt="'+selectkinds+'"]').text(datatext);
      $('#'+selectkinds).val(datavalue);
      $('[data-mockselect="'+selectkinds+'"]').slideUp(100);
      let parentMockselect = $(this).parent('div').attr('data-mockselect');
      //console.log('parentMockselect:', parentMockselect);
      if(parentMockselect == 'sortby'){
        myJp('1');
      }else{
        updateResult();
      }
    });

    $("body").on("click",function(event){
      if(!$(event.target).closest('label').length){
        $('[data-mockselect]').slideUp(100);
      }
    })


    $('#check-remove').off('click').on('click', function () {
      $('[data-ckids]').prop('checked',this.checked);
    });


    //詳細リンク（大外のulクリック）
    $('[data-mylink]').off('click').on('click', function () {
      let myId = $(this).attr('data-mylink');
      //console.log('myId:', myId);
      location.href='/building/detail/?API_ROOM_ID='+myId;
      //$('[data-mydetail="'+myId+'"]').click();
    });



    // toggle
      const $toggle = $('.rgs_filter_toggle');
      const $filterBlock = $('#rgs_filterToggle01');

      $toggle.off('click').on('click', function () {
        const isOpen = $filterBlock.is(':visible');
        if (isOpen) {
          $filterBlock.slideUp(200);
          $toggle.removeClass('open');
        } else {
          $filterBlock.slideDown(200);
          $toggle.addClass('open');
        }
      });

    //残り〇〇件を表示する
    myNokoriDsp();

    let mySeparator = '／';

    //ベースURL
    let sBaseApiUrl='/yw/';




    //モーダル
    setModal();


    $('[data-pagerarea]').css('display', 'none');//ページナビ非表示


    function myJp(page){
      let r = searchBtn();
      //console.log('r.join().length:', r.join('').length);
      //console.log('r:', r);
/*
*/
      if(r.join('').length > 0){
        let param = r.join('&')+'&page='+page+'&sortby='+$('select[name="sortby"]').val();
        param = param.replace('&&&', '&').replace('&&', '&');

        if(location.href.indexOf('/search/search') !== -1){
          if($('#this_file_name').val().length > 0){
            location.href='./search?school='+$('#this_file_name').val()+'?'+param;
          }else{
            location.href='./search?'+param;
          }
        }else{
          location.href='./'+$('#this_file_name').val()+'?'+param;
        }

      }else{
        if(location.href.indexOf('/search/search') !== -1){
          if($('#this_file_name').val().length > 0){
            location.href='./search?school='+$('#this_file_name').val();
          }else{
            location.href='./search';
          }
        }else{
          location.href='./'+$('#this_file_name').val();
        }
      }
    }

    //$('select[name="sortby"]').off('change');
    //$('select[name="sortby"]').on('change', function() {
    //  myJp('1');
    //});
    $('[data-mybtn]').off('click').on('click', function() {
      let mybtn = $(this).attr('data-mybtn');
      let selpage = $(this).attr('data-selpage');
      //console.log('mybtn:', mybtn);
      //console.log('selpage1:', selpage);
      selpage = selpage - 0;
      if(mybtn == 'pager_back'){
        selpage = selpage - 1;
        selpage = (selpage < 1) ? 1 : selpage;
      }else if(mybtn == 'pager_next'){
        selpage = selpage + 1;
      }
      //console.log('selpage2:', selpage);
      myJp(selpage);
    });


    //お気に入り、お問い合わせ
    myFav();


    $('#search_change_btn').off('click');
    $('#search_change_btn').on('click', function(){
      //console.log('search_change_btn');

      let r = searchBtn();
      //console.log('r:', r.join('&'));
      if(r.join('').length > 0){
        let param = $('#this_file_name').val()+'&'+r.join('&');
        param = param.replace('&&&', '&').replace('&&', '&');

        //location.href='/search/search?school='+$('#this_file_name').val()+'&'+r.join('&')+'&myresult='+$('[data-mycounter]').attr('data-mycounter');
        location.href='/search/search?school='+param;
      }
    });

    //フリーワード検索クリア
    $('#keyword_clear_btn').off('click').on('click', function(){
      $('#keyword').val('');
      setTimeout(function(){//遅延実行
        updateResult();
      },5);
    });

    //すべてクリア
    $('[data-search_clear_btn]').off('click').on('click', function(){
      if(confirm('検索条件をすべて解除します。よろしいですか？')){
        regionClear();
        stationlineClear();
        checkBoxClear('region');
        checkBoxClear('stationline');
        checkBoxClear('detail');
        checkBoxClear('special');
        ckClearBtn();

        //$('#search_btn').click();

        //location.href='#search';
        let str = '';
        let thisUrl = window.location.href;
        if(thisUrl.indexOf('__search__') !== -1){
          str = '__search__';
        }

        myJp('1');

      }
    });


    $('#region_btn').off('click');
    $('#region_btn').on('click', function(){
      //console.log('region_btn');
      $('[data-mymdl="region"]').click();
    });

    $('#region_clear_btn').off('click');
    $('#region_clear_btn').on('click', function(){
      //console.log('region_clear_btn');
      if(confirm('市区町村の選択を解除します。よろしいですか？')){
        regionClear();
        checkBoxClear('region');
        //ckClearBtn();
        ////updateResult();
        //location.href='./'+$('#this_file_name').val();
        myJp('1');

      }
    });
    function regionClear(){
        $('[data-category="region"]').html('');
        $('#region').val('');
        //ckClearBtn();
    }

    $('#stationline_btn').off('click');
    $('#stationline_btn').on('click', function(){
      //console.log('stationline_btn');
      $('[data-mymdl="stationline"]').click();
    });

    $('#stationline_clear_btn').off('click');
    $('#stationline_clear_btn').on('click', function(){
      //console.log('stationline_clear_btn');
      if(confirm('沿線・駅の選択を解除します。よろしいですか？')){
        stationlineClear();
        checkBoxClear('stationline');
        //ckClearBtn();
        ////updateResult();
        //location.href='./'+$('#this_file_name').val();
        myJp('1');
      }
    });
    function stationlineClear(){
        $('[data-category="stationline"]').html('');
        $('#stationline').val('');
        //ckClearBtn();
    }

    //チェックボックス解除
    function checkBoxClear(mode){
      if(mode == 'region'){
        $('[data-wardid]').each(function(){
          $(this).prop('checked', false);
        });
      }
      if(mode == 'stationline'){
        $('[data-parentrosenid]').each(function(){
          $(this).prop('checked', false);
        });
        $('[data-rosenid]').each(function(){
          $(this).prop('checked', false);
        });
      }

      if(mode == 'special'){
        $('#special').val('');
        $('[data-myparam^="special"]').each(function(){
          $(this).prop('checked', false);
        });
      }

      if(mode == 'detail'){
        $('[data-myparam]').each(function(){

          let tagName = $(this).prop("tagName").toLowerCase();
          if(tagName == 'input'){
            let typeName = $(this).attr('type').toLowerCase();
            if(typeName == 'radio'){
              $(this).prop('checked', false);
            }else if(typeName == 'checkbox'){
              $(this).prop('checked', false);
            }else{
              $(this).val('');
            }
          }
          if(tagName == 'select'){
            $(this).val('');
          }

        });
      }

    }

    ckClearBtn();




    $('.rgs_filterblock').off('change');
    $('.rgs_filterblock').on('change', function() {
      updateResult();
    });

    function updateResult(mode = ''){
      let r = searchBtn();
      let myType = 'gakusei';
      let zipArr = [];
      let zipStr = '';
      if($('#this_file_name').val().length > 0){
        myType = 'gakusei_universe';
        zipJsonData = $.parseJSON(decodeURI($('#school_data').val()));
        //console.log('zipJsonData:', zipJsonData);

        let arr = $.parseJSON(zipJsonData['zip_json']);
        //console.log('arr:', arr);
        $.each(arr, function(i, v) {
          //console.log(i + ': ' + v);
          zipArr.push(v);
        });
        zipStr = zipArr.join('_')
      }

      let param = r.join('&')+'&type='+myType+'&zip_json='+zipStr;
      param = param.replace('&&&', '&').replace('&&', '&');
      //console.log('param:', param);
      let myCnt = $('.rgs_result_num').attr('data-mycounter');
      let myF = false;
      if(myCnt.length > 0 && myCnt - 0 > 0){
         myF = true;
      }else{
         if(mode != '1'){
           myF = true;
         }
      }
      if(myF){
//const start = performance.now();
        $.ajax({
          type: 'post',
          url: '/yw/ajax/ajax_rw_showListNew.php?'+param,
          dataType: 'json',
          async: false,
          success: function(aRes){
//const end = performance.now();
//console.log('TIME:', end - start);
            //console.log('aRes:', aRes);
            if(aRes){

              //$('.rgs_filter_num').html('0');
              //$('.rgs_result_num').html('0');
              let resultElm1 = $('.rgs_result_num');
              //resultElm1.html('0');
              if(aRes.status){
                  let cnt = aRes.allcnt + '';//aRes.roomcnt
                  cnt = cnt.replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
                  //$('.rgs_filter_num').html(cnt);
                  //$('.rgs_result_num').html(cnt);
                  resultElm1.attr('data-mycounter', cnt);
                  myCounter(resultElm1);

                  if(mode == '1'){
                    let cntStr = cnt;
                    cntStr = cntStr.replace(',', '');
                    cntStr = Number(cntStr).toLocaleString();
                    $('.rgs_sort_num').text(cntStr);
                    $('.rgs_filter_num').text(cntStr);
                  }

              }else{
                  if(aRes.message){
                      //alert(aRes.message);
                      //console.log('aRes.message:', aRes.message);
                  }else{
                    let cnt = aRes.allcnt + '';//aRes.roomcnt
                    cnt = cnt.replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
                    resultElm1.attr('data-mycounter', cnt);
                    myCounter(resultElm1);
                  }
              }

            }
          },
          error: function(XMLHttpRequest, textStatus, errorThrown){
            //alert( errorThrown );
          }
        });
      }
    }

    //カウントアップ表示
    function myCounter(p){

      let countSpeed = 5;
      let countUp = 5;

      let countMax = p.attr('data-mycounter').replace(',', '');
      let thisCount = p.text().replace(',', '');

      let plusF = true;
      let sa = thisCount - countMax;
      if(sa > 0){
        plusF = false;
      }else{
        sa = sa * -1
      }
      let amari = sa % 10;
      //console.log('sa:', sa, 'amari:', amari);
      if(sa < amari){sa = sa - amari;}
      countUp = Math.ceil(sa / 10);
      //console.log('countUp:', countUp);

      //if((countMax - 0) < (thisCount - 0)){plusF = false;}
      let countTimer;

      //console.log('countMax:', countMax, 'thisCount:', thisCount);
      function timer(p){
          countTimer = setInterval(function(){
              let countNext;
              if(plusF){
                thisCount = (thisCount - 0) + countUp;
                //console.log('thisCount:', thisCount);
                countNext = thisCount;
                if(countNext > countMax){countNext = countMax;}
              }else{
                thisCount = (thisCount - 0) - countUp;
                //console.log('thisCount:', thisCount);
                countNext = thisCount;
                if(countNext < countMax){countNext = countMax;}
              }
              p.text(Number(countNext).toLocaleString());
              //console.log('countNext:', countNext);

              if(countNext == countMax){
                  clearInterval(countTimer);
              }
          },countSpeed);
      }
      timer(p);

    }






    //モーダル
    function setModal(){
      $('[data-mymdl]').each(function(){
        var myBtn   = $(this).attr('data-mymdl');
        var myNo    = $(this).attr('data-myno');
        var myTitle = $(this).attr('data-mdl_title');
        var myMsg   = $(this).attr('data-mdl_msg');
        var myId    = $(this).attr('data-my_id');
        var myData  = $(this).attr('data-my_data');

        //console.log('myBtn:', myBtn, 'myNo:', myNo );

        var myMdlId = myNo;
        if(myNo.indexOf('delete_') !== -1){
          myMdlId = 'delete';
        }

        $('[data-mymdl="'+myBtn+'"]').modaal({
          hide_close     : true,
          overlay_close  : false,
          background : '#000000',
          overlay_opacity: 0.3,
          type           : 'inline',
          content_source : '#mdlcts'+myMdlId,
          before_open : function(){
            //モーダルオープン時の処理
            //モーダルタイトル
            $('#mdl_title_'+myMdlId).text(myTitle);
            setModalInit(myNo, myId, myData, myMsg, myBtn);
          },
          after_open : function(){
            //モーダル内ボタン イベントセット
            var myId2 = $('#id_staff').val();
            setModalBtn(myNo, myId2, myData, myBtn);
          },
          before_close : function(){
            //モーダルクローズ時の処理
          },

        });
      });

    }
    //モーダル内初期値セット
    function setModalInit(myNo, myId, myData, myMsg, myBtn){
      //市区町村 選択の場合
      if(myNo == 'region'){
        //let myId = null;
        //$('#id_info').val(myId);
      }
      //沿線・駅 選択の場合
      if(myNo == 'stationline'){
        //let myId = null;
        //$('#id_info').val(myId);
      }


      if(myNo == 'region' || myNo == 'stationline'){

        $('.rgs_diside').removeClass('on');

        //チェック状態の保存
        $('[data-oldchecked]').each(function(){
          let onoff = '';
          if($(this).prop('checked')){
            onoff = 'ON';
          }else{
            onoff = 'OFF';
          }
          $(this).attr('data-oldchecked', onoff);
        });
      }


    }

    //モーダル内ボタン イベントセット
    function setModalBtn(myNo, myId, myData, myBtn){

      var mySelector1 = '';
      var mySelector2 = '';
      var mySelector3 = '';
      var mySelector4 = '';
      var myFunc1 = function(){};
      var myFunc2 = function(){};
      var myFunc3 = function(){};
      var myFunc4 = function(){};

      var myFuncOldChecked = function(){
        //console.log('myFunc1');
        $('[data-mymdl]').modaal('close');
      };

      if(myNo == 'region' || myNo == 'stationline'){

        //チェック状態の更新チェック
        myFuncOldChecked = function(){
          let ckF = false;
          $('[data-oldchecked]').each(function(){
            let checked = $(this).prop('checked');
            let onoff   = $(this).attr('data-oldchecked');
            if((checked && onoff == 'OFF') || (!checked && onoff == 'ON')){
              ckF = true;
              return;
            }
          });

          let closeF = true;

          if(ckF){
            closeF = false;
            if(confirm('「決定」を押さずに閉じようとしています。\n変更を破棄して閉じてよろしいですか？')){
              closeF = true;
              //変更を破棄
              $('[data-oldchecked]').each(function(){
                let onoff   = $(this).attr('data-oldchecked');
                let checked = false;
                if(onoff == 'ON'){
                  checked = true;
                }
                $(this).prop('checked', checked);
              });
            }
          }

          if(closeF){
            //console.log('myFunc1');
            $('[data-mymdl]').modaal('close');
          }
        };

        //チェック状態の変更イベント
        $('[data-oldchecked]').each(function(){
          $(this).off('change').on('change', function(){
            $('.rgs_diside').addClass('on');
          });
        });

      }


      //キャンセルボタン
      mySelector1 = '.rgs_cancel';
      myFunc1 = myFuncOldChecked;

      //×ボタン
      mySelector3 = '.rgs_clsbtn';
      myFunc3 = myFuncOldChecked;

      //全選択解除ボタン
      mySelector4 = 'button.rgs_crear';
      myFunc4 = function(){
        //console.log('myFunc4');
        $('[data-oldchecked]').each(function(){
          if($(this).prop('checked')){
            $('.rgs_diside').addClass('on');
          }
          $(this).prop('checked', false);
        });
      };


      //市区町村 選択の場合
      if(myNo == 'region'){

        //決定ボタン
        mySelector2 = 'button.rgs_diside';
        myFunc2 = function(){
          //console.log('myFunc2');
          let r = [];
          let d1 = [];
          $('[data-wardid]').each(function(){
            if($(this).prop('checked')){
              let wardId = $(this).attr('data-wardid');
              r.push(wardId);
              d1.push($(this).val());
            }
          });
          let param  = 'area[]=' + r.join('&area[]=');
          $('#region').val(param);

          //console.log('d1:', d1);
          //console.log('d2:', d2);
          let dspStr = d1.join(mySeparator)+'<br>';
          $('[data-category="region"]').html(dspStr);
          ckClearBtn();
          $('[data-mymdl]').modaal('close');
          updateResult();

        };

      }


      //沿線・駅 選択の場合
      if(myNo == 'stationline'){

        $('[data-parentrosenid]').off('click');
        $('[data-parentrosenid]').on('click', function(){
          let rosenId = $(this).attr('data-parentrosenid');
          let onoff = true;
          if($(this).prop('checked')){
            onoff = false;
            $('[data-rosenid="'+rosenId+'"]').each(function(){
              $(this).prop('checked', onoff);
            });
          }else{
            onoff = true;
          }
        });
        $('[data-stationid]').off('click');
        $('[data-stationid]').on('click', function(){
          let rosenId = $(this).attr('data-rosenid');
          let stationId = $(this).attr('data-stationid');
          let onoff = true;
          if($(this).prop('checked')){
            onoff = false;
            $('[data-parentrosenid="'+rosenId+'"]').each(function(){
              $(this).prop('checked', onoff);
            });
          }
        });
        //路線選択のアコーディオン
        $('[data-rosenaccordion]').off('click').on("click",function(){
          var acodnid = $(this).attr("data-rosenaccordion");
          $('[data-onoff="'+acodnid+'"]').fadeToggle();
          $(this).toggleClass("active");
        });


        //決定ボタン
        mySelector2 = 'button.rgs_diside';
        myFunc2 = function(){
          //console.log('myFunc2');
          let r = [];
          let d1 = [];
          let d2 = [];
          $('[data-parentrosenid]').each(function(){
            if($(this).prop('checked')){
              let rosenId = $(this).attr('data-parentrosenid');
              r.push(rosenId);
              d1['A'+rosenId] = $(this).val();
            }
          });
          $('[data-stationid]').each(function(){
            if($(this).prop('checked')){
              let rosenId = $(this).attr('data-rosenid');
              let str = rosenId + ',' + $(this).attr('data-stationid');
              r.push(str);
              let str1 = $('[data-parentrosenid="' + rosenId + '"]').val();
              d1['A'+rosenId] = str1;
              //console.log('rosenId:', rosenId);
              //console.log('d2[rosenId]:', d2[rosenId]);
              if(!d2['A'+rosenId]){d2['A'+rosenId] = [];}
              d2['A'+rosenId].push($(this).val());
            }
          });
          let param  = 'line[]=' + r.join('&line[]=');
          $('#stationline').val(param);

          //console.log('d1:', d1);
          //console.log('d2:', d2);

          let dspStr = '';
          for(let k in d1){
            //console.log('k:', k);
            if(d2[k]){
              //console.log('d2:', d2);
              dspStr += d1[k]+'：'+d2[k].join(mySeparator)+'<br>';
            }else{
              dspStr += d1[k]+'<br>';
            }
          };
          $('[data-category="stationline"]').html(dspStr);
          ckClearBtn();
          $('[data-mymdl]').modaal('close');
          updateResult();

        };
      }

      $(mySelector1).off('click');
      $(mySelector1).on('click', myFunc1);

      $(mySelector2).off('click');
      $(mySelector2).on('click', myFunc2);

      $(mySelector3).off('click');
      $(mySelector3).on('click', myFunc3);

      $(mySelector4).off('click');
      $(mySelector4).on('click', myFunc4);

    }



    $('#search_btn').off('click');
    $('#search_btn').on('click', function(){
      //console.log('search_btn');
      let r = searchBtn();
      //console.log('r:', r.join('&'));
      let param = $('#this_file_name').val();
      if(r.join('').length > 0){
        param = param+'?'+r.join('&');
      }
      param = param.replace('&&&', '&').replace('&&', '&');
      if($('#this_file_name').val().length > 0){
        location.href='/universe/'+param;
      }else{
        location.href='./'+param;
      }

    });

    var p = GetQueryString();

    setQuery(p);
    setQuery2();
    getSearchQuery(p);

    function searchBtn() {
        let r = [];
        let dat = '';
        $('[data-myparam]').each(function(){
          let myParam = $(this).attr('data-myparam');
          let id = $(this).attr('id');
          let tagName = $(this).prop("tagName").toLowerCase();
          if(tagName == 'input'){
            let typeName = $(this).attr('type').toLowerCase();
            if(typeName == 'radio'){
              //dat = $(this).val();
              dat = '';
              if(id.length > 0){
                dat = $('#'+id+':checked').val();
              }
            }else if(typeName == 'checkbox'){
              if(id.length > 0){
                dat = $('#'+id+':checked').val();
              }
            }else{
              dat = $(this).val();
            }
          }
          if(tagName == 'select'){
            dat = $(this).val();
          }
          if(dat && dat !== undefined && dat.length > 0){
            //console.log('id:', id, 'myParam:', myParam, 'dat:', dat);
            r.push(myParam+'='+dat);
          }
          if(myParam == 'layout[]' && dat == '4K-'){
            r.push('layout[]=410');//4Kを追加
            r.push('layout[]=420');//4DKを追加
            r.push('layout[]=430');//4LDKを追加
            r.push('layout_more=1');//5K以上を追加
          }
        });
        r.push($('#region').val());
        r.push($('#stationline').val());
        //r.push($('#special').val());

        let f = 0;
        for(let i=0;i<r.length;i++){
          //console.log('i:', i, 'r:', r[i]);
          if(r[i] == 'built_max=1'){f = 1;}
        }
        r2 = [];
        if(f == 0){
          for(let i=0;i<r.length;i++){
            //console.log('i:', i, 'r:', r[i]);
            if(r[i] == 'built_min=1'){
            }else{
              r2.push(r[i]);
            }
          }
          return r2;
        }else{
          return r;
        }
    }

    function getSearchQuery(p) {
    
    //console.log('p:', p);
    
        if(p!=null) {
            if(p['area']) _getAreaList(p['area']);
            if(p['line']) _getTrainList(p['line']);
    
            var cond_name='';
            if(p['keyword']) cond_name+=p['keyword'];
            if(parseInt(p['rent_min'])) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=p['rent_min']+'万円';
            } else {
              if(parseInt(p['rent_max'])){
                if(cond_name) cond_name+=mySeparator;
              }
                //cond_name+='下限なし';
            }
            if(parseInt(p['rent_max'])) {
                cond_name+='～';
                cond_name+=p['rent_max']+'万円';
            } else {
              if(parseInt(p['rent_min'])){
                cond_name+='～';
              }
                //cond_name+='上限なし';
            }
            if($('#cb-01').prop('checked')) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+='共益費込';
            }
            if($('#cb-02').prop('checked')) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+='駐車場代込';
            }
            if($('#cb-03').prop('checked')) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+='敷金なし';
            }
            if($('#cb-04').prop('checked')) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+='敷金礼金なし';
            }
            if($('#cb-04b').prop('checked')) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+='礼金なし';
            }
            var madori='';
            var madori_array=[];
            madori_array.push({name:'cb-05', title:'1R'});
            madori_array.push({name:'cb-06', title:'1K'});
            madori_array.push({name:'cb-07', title:'1DK'});
            madori_array.push({name:'cb-08', title:'1LDK'});
            madori_array.push({name:'cb-09', title:'2K'});
            madori_array.push({name:'cb-10', title:'2DK'});
            madori_array.push({name:'cb-11', title:'2LDK'});
            madori_array.push({name:'cb-12', title:'3K'});
            madori_array.push({name:'cb-13', title:'3DK'});
            madori_array.push({name:'cb-14', title:'3LDK'});
            madori_array.push({name:'cb-15', title:'4K'});
            madori_array.push({name:'cb-16', title:'4DK'});
            madori_array.push({name:'cb-17', title:'4LDK'});
            madori_array.push({name:'cb-18', title:'5K以上'});
            madori_array.push({name:'cb-4K-', title:'4K以上'});
            $.each(madori_array, function(index, value){
                if($('#'+value.name).prop('checked')) {
                    if(madori) madori+=',';
                    madori+=value.title;
                }
            });
            if(madori) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=madori;
            }
            if(parseInt(p['built_min'])) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=p['built_min']+'年';
            } else {
              if(parseInt(p['built_max'])){
                if(cond_name) cond_name+=mySeparator;
              }
                //if(cond_name) cond_name+=mySeparator;
                //cond_name+='指定なし';
            }
            if(parseInt(p['built_max'])) {
                //if(cond_name) cond_name+=mySeparator;
                //cond_name+='～';
                if(p['built_max'] == 1){
                  cond_name+='新築';
                }else{
                  cond_name+=p['built_max']+'年';
                }
            } else {
                //if(cond_name) cond_name+=mySeparator;
                //cond_name+='～';
                //cond_name+='指定なし';
            }
            if(parseInt(p['station_walk'])) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=p['station_walk']+'分';
            } else {
                //if(cond_name) cond_name+=mySeparator;
                //cond_name+='指定なし';
            }
            if(parseInt(p['dimension_min'])) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=p['dimension_min']+'㎡';
            } else {
              if(parseInt(p['dimension_max'])){
                if(cond_name) cond_name+=mySeparator;
              }
                //cond_name+='下限なし';
            }
            if(parseInt(p['dimension_max'])) {
                cond_name+='～';
                cond_name+=p['dimension_max']+'㎡';
            } else {
              if(parseInt(p['dimension_min'])){
                cond_name+='～';
              }
                //cond_name+='上限なし';
            }
            var special='';
            var special_array=[];
            special_array.push({name:'cb-19', title:'リノベーション物件'});
            special_array.push({name:'cb-20', title:'学生おすすめ物件'});
            special_array.push({name:'cb-21', title:'おすすめ物件'});
            special_array.push({name:'cb-22', title:'新着物件'});
            //special_array.push({name:'cb-23', title:'外国人おすすめ物件'});
            special_array.push({name:'cb-51', title:'飲食店舗特集'});
            special_array.push({name:'cb-52', title:'テナントおすすめ物件'});
            special_array.push({name:'cb-53', title:'オートロック'});
            special_array.push({name:'cb-54', title:'洗面所独立'});
            special_array.push({name:'cb-55', title:'南向き'});
            special_array.push({name:'cb-56', title:'追焚機能'});
            special_array.push({name:'cb-252', title:'360°パノラマ画像あり'});



            special_array.push({name:'equip_30' , title:'フローリング'});
            special_array.push({name:'equip_10' , title:'クローゼット'});
            special_array.push({name:'equip_15' , title:'シューズボックス'});
            special_array.push({name:'equip_28' , title:'室内洗濯機置き場'});
            special_array.push({name:'equip_31' , title:'ロフト'});
            special_array.push({name:'equip_95' , title:'エアコン'});
            special_array.push({name:'equip_32' , title:'バルコニー'});
            special_array.push({name:'equip_13' , title:'専用庭'});
            special_array.push({name:'equip_69' , title:'宅配ボックス'});
            special_array.push({name:'equip_5' , title:'エレベータ'});
            special_array.push({name:'equip_38' , title:'駐車場有'});
            special_array.push({name:'equip_57' , title:'楽器相談'});
            special_array.push({name:'equip_33' , title:'ペット可'});
            special_array.push({name:'equip_80' , title:'分譲賃貸'});
            special_array.push({name:'equip_189' , title:'2階以上'});
            special_array.push({name:'equip_18' , title:'システムキッチン'});
            special_array.push({name:'equip_16' , title:'ガスコンロ対応'});
            special_array.push({name:'equip_29' , title:'バス・トイレ別'});
            special_array.push({name:'equip_27' , title:'シャワー付きトイレ'});
            special_array.push({name:'equip_25' , title:'追焚機能'});
            special_array.push({name:'equip_26' , title:'浴室乾燥機'});
            special_array.push({name:'equip_21' , title:'独立洗面'});
            special_array.push({name:'equip_22' , title:'シャンプードレッサー'});
            special_array.push({name:'equip_129' , title:'インターネット対応'});
            special_array.push({name:'equip_3' , title:'CATV'});
            special_array.push({name:'equip_2' , title:'CS'});
            special_array.push({name:'equip_1' , title:'BS'});
            special_array.push({name:'equip_7' , title:'オートロック'});
            special_array.push({name:'equip_8' , title:'モニター付きインターホン'});
            special_array.push({name:'equip_73' , title:'南向き'});
            special_array.push({name:'equip_252' , title:'パノラマあり'});
            special_array.push({name:'equip_34' , title:'デザイナーズ物件'});
            special_array.push({name:'equip_256' , title:'インターネット無料'});

            special_array.push({name:'special3' , title:'新着物件'});

            //special_array.push({name:'built_max' , title:'新築物件'});

            $.each(special_array, function(index, value){
                if($('#'+value.name+', #'+value.name+'_2').prop('checked')) {
                    if(special) special+=mySeparator;
                    special+=value.title;
                }
            });


            if(special) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=special;
            }
            var pop='';
            var pop_array=[];
            pop_array.push({name:'cb-41', title:'バス・トイレ別'});
            pop_array.push({name:'cb-42', title:'2階以上'});
            pop_array.push({name:'cb-43', title:'駐車場あり'});
            pop_array.push({name:'cb-44', title:'室内洗濯機置場'});
            pop_array.push({name:'cb-45', title:'エアコン付き'});
            pop_array.push({name:'cb-46', title:'ペット飼育可'});
            pop_array.push({name:'cb-47', title:'オートロック'});
            pop_array.push({name:'cb-48', title:'洗面所独立'});
            pop_array.push({name:'cb-49', title:'南向き'});
            pop_array.push({name:'cb-50', title:'追焚機能'});
            $.each(pop_array, function(index, value){
                if($('#'+value.name).prop('checked')) {
                    if(pop) pop+=',';
                    pop+=value.title;
                }
            });
            if(pop) {
                if(cond_name) cond_name+=mySeparator;
                cond_name+=pop;
            }



    
            $('[data-category="other"]').html(cond_name);
            ckClearBtn();
        }
    }


    function _getAreaList(area){
        var aData = {}, sUrl = sBaseApiUrl + 'ajax/ajax_rw_showList_area.php';
        aData.area = area;
        $.ajax({
            type: 'post',
            url: sUrl,
            data: aData,
            dataType: 'json',
            async: false,
            success: function(aRes){
                if(aRes){
                    if(aRes.status){
                        var area_name='';
                        $.each(area, function(index, value){
                            var area_cd=value;
                            $.each(aRes.area, function(index, value){
                                if(value[area_cd]) {
                                    if(area_name) area_name+=mySeparator;
                                    area_name+=value[area_cd];
                                }
                            });
                        });
                        if(area_name) {
                            $('[data-category="region"]').html(area_name);
                            ckClearBtn();
                        }
                    }else{
                        if(aRes.message){
                            //alert(aRes.message);
                        }
                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                //alert( errorThrown );
            }
        });
    }
    function _getTrainList(line){
        var aData = {}, sUrl = sBaseApiUrl + 'ajax/ajax_rw_showList_train.php';
        aData.line = line;
        aData.mySeparator = mySeparator;
        $.ajax({
            type: 'post',
            url: sUrl,
            data: aData,
            dataType: 'json',
            async: false,
            success: function(aRes){
                if(aRes){
                    if(aRes.status){
                        var area_name = aRes.line2.join('<br>');
                        if(area_name) {
                            $('[data-category="stationline"]').html(area_name);
                            ckClearBtn();

                        }
                    }else{
                        if(aRes.message){
                            //alert(aRes.message);
                        }
                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                //alert( errorThrown );
            }
        });
    }

    function setQuery(p) {
//console.log('p:', p);
    
        if(p != null) {
            var param='';
            var base_url='';

            var paramArea = '';
            var paramLine = '';
            var paramSpecial = '';
    
            $.each(p, function(index, value){

                if(index=='sortby'){
                  $('#sortby').val(value);
                }
                if(index=='page' || index=='resultcount' || index=='sortby') return true;
                if(index=='area') {
                    if($.isArray(value)) {
                        paramArea = 'area[]=' + value.join('&area[]=');
                        $.each(value, function(index2, value2){
                          $('[data-wardid="'+value2+'"]').prop('checked', true);
                        });
                    } else {
                        paramArea = 'area[]=' + value;
                        $('[data-wardid="'+value+'"]').prop('checked', true);
                    }
                } else if(index=='line') {
                    if($.isArray(value)) {
                        paramLine = 'line[]=' + value.join('&line[]=');
                        $.each(value, function(index2, value2){
                          subSetCheckBox(value2);
                        });
                    } else {
                        paramLine = 'line[]=' + value;
                        subSetCheckBox(value);
                    }
                } else if(index=='special') {
                    if($.isArray(value)) {
                        paramSpecial = 'special[]=' + value.join('&special[]=');
                        $.each(value, function(index2, value2){
                          $('[id="special'+value2+'"]').prop('checked', true);
                        });
                    } else {
                        paramSpecial = 'special[]=' + value;
                        $('[id="special'+value+'"]').prop('checked', true);
                    }
                }
            });
            $('#region').val(paramArea);
            $('#stationline').val(paramLine);
            $('#special').val(paramSpecial);
    
            $('#lease_for_years_type').prop('checked', true);
            $('[data-myparam]').each(function(){
    
              //let id = $(this).attr('id');
              let id = $(this).attr('data-myparam');
              let tagName = $(this).prop("tagName").toLowerCase();
              if(tagName == 'input'){
                let typeName = $(this).attr('type').toLowerCase();
    
                    //let str = $(this).attr('data-myparam');
                      //console.log('str:', str);
                      //console.log('p[id]:', p[id]);
                //id
                if (p[id] !== undefined && p[id] !== 'undefined' && id.length > 0) {
                  if(typeName == 'radio'){
                    //dat = $(this).val();
                    if(id == 'lease_for_years_type'){
                      $('#lease_for_years_type'+p[id]).prop('checked', true);
                    }

                    //$('[name="'+str+'"]').val(p[id]);

                  }else if(typeName == 'checkbox'){
                    if(p[id] == $('#'+id).val()){
                      $('#'+id).prop('checked', true);
                    }
                    if(p[id] == $('#'+id+'_2').val()){
                      $('#'+id+'_2').prop('checked', true);
                    }
                    if(id == 'built_max'){
                      //console.log('id:', id);
                      //console.log('p[id]:', p[id]);
                    }
                  }else{
                    $('#'+id).val(p[id]);
                  }
    
                }
              }
              if(tagName == 'select'){
                $('#'+id).val(p[id]);
              }
    
    
            });

    
            //checkbox
            $.each(p['rent_cond'], function(index, value){
                if(value=='1') $('#cb-01').prop('checked', true);
                if(value=='2') $('#cb-02').prop('checked', true);
                if(value=='3') $('#cb-04').prop('checked', true);
                if(value=='4') $('#cb-03').prop('checked', true);
                if(value=='5') $('#cb-04b').prop('checked', true);
            });
            $.each(p['layout'], function(index, value){
                if(value=='100') $('#cb-05').prop('checked', true);
                if(value=='110') $('#cb-06').prop('checked', true);
                if(value=='120') $('#cb-07').prop('checked', true);
                if(value=='130') $('#cb-08').prop('checked', true);
                if(value=='210') $('#cb-09').prop('checked', true);
                if(value=='220') $('#cb-10').prop('checked', true);
                if(value=='230') $('#cb-11').prop('checked', true);
                if(value=='310') $('#cb-12').prop('checked', true);
                if(value=='320') $('#cb-13').prop('checked', true);
                if(value=='330') $('#cb-14').prop('checked', true);
                if(value=='410') $('#cb-15').prop('checked', true);
                if(value=='420') $('#cb-16').prop('checked', true);
                if(value=='430') $('#cb-17').prop('checked', true);
                if(value=='4K-') $('#cb-4K-').prop('checked', true);
            });
            if(p['layout_more'] !== undefined && p['layout_more']) {
                $('#cb-18').prop('checked', true);
            }
            $.each(p['special'], function(index, value){
                if(value=='1') $('#cb-19').prop('checked', true);
                if(value=='2') $('#cb-20').prop('checked', true);
                if(value=='4') $('#cb-21').prop('checked', true);
                if(value=='3') $('#cb-22').prop('checked', true);
                //if(value=='5') $('#cb-23').prop('checked', true);
                if(value=='6') $('#cb-51').prop('checked', true);
                if(value=='7') $('#cb-52').prop('checked', true);
                if(value=='8') $('#cb-53').prop('checked', true);
                if(value=='9') $('#cb-54').prop('checked', true);
                if(value=='10') $('#cb-55').prop('checked', true);
                if(value=='11') $('#cb-56').prop('checked', true);
            });
            var eq = [
                //間取り
                13, 30, 31, 32, 45
                //冷暖房
                , 63, 95,
                //収納
                , 10, 11, 15, 62, 92
                //管理防犯
                , 6, 7, 8, 9, 69, 125
                //キッチン
                , 16, 17, 18, 96, 131, 132, 133, 134
                //洗面・浴室・トイレ
                , 21, 22, 25, 26, 27, 29, 75, 91, 93, 163, 170, 171
                //情報設備・回線 // 256追加 2023-04-28 bitlarge
                , 256, 1, 2, 3, 123, 129
                //建物設備
                , 5, 36, 40
                //その他
                , 20, 33, 126, 196, 197, 198, 252, 150
                , 28, 38, 57, 80, 189, 73, 34, 256, 230
            ];
            $.each(p['equipment'], function(index, value){
                if(value=='29') $('#cb-30,#cb-41').prop('checked', true);
                if(value=='189') $('#cb-31,#cb-42').prop('checked', true);
                if(value=='36') $('#cb-32,#cb-43').prop('checked', true);
                if(value=='28') $('#cb-33,#cb-44').prop('checked', true);
                if(value=='95') $('#cb-34,#cb-45').prop('checked', true);
                if(value=='33') $('#cb-35,#cb-46').prop('checked', true);
                if(value=='7') $('#cb-47').prop('checked', true);
                if(value=='127') $('#cb-48').prop('checked', true);
                if(value=='73') $('#cb-49').prop('checked', true);
                if(value=='25') $('#cb-50').prop('checked', true);
                if(value=='252') $('#cb-252').prop('checked', true);
                var eq_input=value;
                $.each(eq, function(index, value){
                    if(eq_input==value){
                      $('#equip_'+value).prop('checked', true);
                      $('#equip_'+value+'_2').prop('checked', true);
                    }
                });
            });
            $.each(p['buildingtype'], function(index, value){
                if(value=='1') $('#cb-36').prop('checked', true);
                if(value=='2') $('#cb-37').prop('checked', true);
                if(value=='3') $('#cb-38').prop('checked', true);
                if(value=='4') $('#cb-39').prop('checked', true);
                if(value=='5') $('#cb-40').prop('checked', true);
            });
        }
    }
    function setQuery2() {
      $('[data-selectbox]').each(function(){
        let selectkinds = $(this).attr('data-selectbox');
        let datatext = $('#'+selectkinds+' option:selected').text();

        //console.log('selectkinds:', selectkinds, 'datatext:', datatext);

        if(datatext.length == 0){
          datatext = $('#'+selectkinds+' option:first').text();
        }
        $('[data-txt="'+selectkinds+'"]').text(datatext);
      });
    }

    function subSetCheckBox(p) {
    
        if(p.indexOf(',') !== -1){
          let id2 = p.split(',');
          $('[data-onoff="'+id2[0]+'"]').css('display', 'block');
          $('[data-rosenid="'+id2[0]+'"][data-stationid="'+id2[1]+'"]').prop('checked', true);
        }else{
          $('[data-parentrosenid="'+p+'"]').prop('checked', true);
        }
    }

    function GetQueryString() {
        if (1 < document.location.search.length) {
            var query = document.location.search.substring(1);
            var parameters = query.split('&');
    
            var result = new Object();
            for (var i = 0; i < parameters.length; i++) {
                var element = parameters[i].split('=');
    
                var paramName = decodeURIComponent(element[0]);
                var paramValue = decodeURIComponent(element[1]);
    
                if(paramName.match(/\[\]$/)) {
                    paramName_index = paramName.replace(/\[\]$/, '');
                    if(result[paramName_index]===undefined) result[paramName_index]=[];
                    result[paramName_index].push(decodeURIComponent(paramValue));
                } else {
                    result[paramName] = decodeURIComponent(paramValue);
                }
            }
                return result;
            }
        return null;
    }

  //件数セット
  let mode = '1';
  if(location.href.indexOf('/search') !== -1 && $('#this_file_name').val().length > 0){
    mode = '';
  }
  if(location.href.indexOf('/universe/') !== -1 || location.href.indexOf('/search') !== -1){
    if(location.href.indexOf('?') !== -1){ mode = '';}
    updateResult(mode);

    /* モーダル内　広島・岡山 順番入れ替え */
    if($('#this_pref').val().indexOf('33') == 0){
      //岡山・広島
      $('.rgs_statusselect').removeClass('rgs_item_hiroshima');
      $('.rgs_statusselect').addClass('rgs_item_okayama');
    }

  }



});//ready


$(window).on('load',function(){
});



    //解除ボタン表示非表示
    function ckClearBtn(){
      if($('[data-category="region"]').text().length > 0){
        $('[data-region_btn="clear"]').css('display', 'block');
      }else{
        $('[data-region_btn="clear"]').css('display', 'none');
      }
      if($('[data-category="stationline"]').text().length > 0){
        $('[data-stationline_btn="clear"]').css('display', 'block');
      }else{
        $('[data-stationline_btn="clear"]').css('display', 'none');
      }
      //data-stationline_btn="select"
    }

    var pagerdspNo = 0;
    //ページナビ
    function myPageNavi(){
      if($('[data-listend]').length == 0){return;}

      let listend = $('[data-listend]').attr('data-listend') - 0;
      if( pagerdspNo > listend ){return false;}

      let myScrollHeight = $(window).scrollTop();
      let winH = $(window).height();

      let objH = $('[data-listend]').outerHeight();
      let objTop = $('[data-listend]').offset().top;
      let objBottom = (objTop + objH) - 200;
      //console.log('objBottom:', objBottom, 'myScrollHeight:', myScrollHeight);

      if (myScrollHeight >= objBottom - winH / 2) {
        pagerdspNo++;
        //console.log('pagerdspNo:', pagerdspNo, 'listend:', listend);
        $('[data-pagerdsp="'+pagerdspNo+'"]').fadeIn();
        if(pagerdspNo > listend ){
          $('[data-pagerarea]').fadeIn();//ページナビ表示
        }
      }
    }


    function myNokoriDsp(){
      //残り〇〇件を表示する
      $('[data-mybldid]').on('click', function(){
        let id = $(this).attr('data-mybldid');
        //console.log('id:', id);
        $('[data-myul="'+id+'"]').slideToggle(100);
        $('[data-myopenbtn="'+id+'"]').toggle();
        $('[data-myclosebtn="'+id+'"]').toggle();

        let myScrollPosition = $('[data-roomlist="'+id+'"]').offset().top - 70;
        //console.log('myScrollPosition:', myScrollPosition);
        let speed = 80;
        $('html, body').animate({scrollTop:myScrollPosition}, speed, 'swing');
        //$('html, body').scrollTop(myScrollPosition);

      });
    }




    function myFav(){

      //お気に入り、お問い合わせ
      $('[data-favdel]').off('click').on('click', function(){

        let roomId = $(this).attr('data-favdel');
        if(roomId == 'all' || roomId == 'contact'){
            let cnt = 0;
            $('[data-ckids]').each(function(){
              if($(this).prop('checked') == true){
                cnt++;
              }
            });
            if(cnt == 0){
              alert('選択されていません。');
              return false;
            }
        }

        if(roomId == 'contact'){
          //console.log('contact:', roomId);
          let params = [];
          $('[data-ckids]').each(function(){
            if($(this).prop('checked') == true){
              let roomId2 = $(this).attr('data-ckids');
              //console.log('roomId2:', roomId2);
              params.push(roomId2);
            }
          });
          location.href='/contact/?room_id[]='+params.join('&room_id[]=');

        }else{

          let funcFav02 = function(roomId, mode){
            //console.log('roomId:', roomId, 'mode:', mode);
            if(roomId == 'all'){
              $('[data-ckids]').each(function(){
                if($(this).prop('checked') == true){
                  let roomId2 = $(this).attr('data-ckids');
                  //console.log('roomId2:', roomId2);
                  let f = true;
                  if(mode == 'allon'){
                    if($('[data-favdel="'+roomId2+'"]').hasClass('fav_icon')){
                      f = false;
                    }
                  }
                  if(f){
                    togglefav($('[data-favdel="'+roomId2+'"]'), roomId2);
                  }
                  $(this).prop('checked', false);
                }
              });
            }else{
              togglefav($('[data-favdel="'+roomId+'"]'), roomId);
            }
          };

          //お気に入り一覧の場合
          if(location.href.indexOf('/favorite') !== -1 ){
            if(confirm('お気に入りから削除します。\nよろしいですか？')){
              funcFav02(roomId, '');
              location.href = './';
            }
          }

          //履歴一覧の場合、建物詳細の場合
          if(location.href.indexOf('/history') !== -1 || location.href.indexOf('/building/?') !== -1){
            funcFav02(roomId, 'allon');
            if(roomId == 'all'){
              $('#check-remove').prop('checked', false);
            }
          }

          //物件詳細の場合、検索結果一覧の場合
          if(location.href.indexOf('/building/detail') !== -1 || location.href.indexOf('/search') !== -1 || location.href.indexOf('/universe/') !== -1){
            togglefav('[data-favdel="'+roomId+'"]', roomId);
          }


        }
      });
    }

