$(function () {
  $('#lessMore').click(function(e) {
    lessMore();
  })
  /**
   * SEARCH
   */
  //click lựa chọn tỉnh thành phố
  $('#province').click(function () {
    if($('.dropdown-menu--filter-areas li').length === 0){
      $.each(json.Cities, function (_key, _data) {
        if(_data.fk_state === '0') {
          $('.dropdown-menu--filter-areas').append(`<li class="single-filter-area">
              <a href="javascript:void(0)" class="single-filter-area__link">
                <div class="area-title" data-id="${_data.id}" data-name="${_data.link_rewrite}">${_data.name}</div>
                <div class="area-count"></div>
              </a>
          </li>`);
        }
      });
    }
  })
  $(document).on('click', '.single-filter-area', function (e) { 
    var province_id = $(this).find('.area-title').data('id');
    var province_rewrite = $(this).find('.area-title').data('name');
    var province_name = $(this).find('.area-title').text();
    $(this).parents('#province').find('.toggle-label').text(province_name)
    $(this).parents('#province').find('.id_provice').val(province_id)
    $(this).parents('#province').find('.name_provice').val(province_rewrite)
    $(this).parents('#province').removeClass("open");
    //build district
    var container = $('.district-list');
    container.empty(); 
    $.ajax({
      url: "/load/DistrictAC",
      dataType: "json",
      type: "GET",
      data: {
        CityId: province_id,
        opt:'',
      },
      success: function (data) {
        data !== null && setTimeout(function () { 
          if(data.Data.length> 0){
            for(i = 0; i < data.Data.length; i++) {
              var district = data.Data[i];
              var item = $('.district-list-template').contents().clone();
              // $('#locationState').find('.id_city').val(district.id);
              // $('#locationState').find('.name-state').text(district.link_rewrite);
              $(item).find('a').text(district.name);
              $(item).find('a').attr('data-slug', district.link_rewrite)
              $(item).find('a').attr('data-id', district.id)
              container.append(item); 
            }			
          } 
        }, 100)
      },
      complete: function () {},
      error: function () {
        console.log("không thấy thông tin quận huyện.")
      }
    })
    // $.ajax({
    //     url: 'https://itro.vn/tim-phong-2/getDistrictByProvince',
    //     type: 'get',
    //     dataType: 'json',
    //     data: {province_id: province},
    //     success: function (response) {
    //         if (response.status == true) {
    //             var dt = response.data;
    //             var container = $('.district-list');
    //             container.empty();
    //             dt.forEach(function (obj) {
    //                 var item = $('.district-list-template').contents().clone();
    //                 $(item).find('.district-value').val(obj.districtid);
    //                 $(item).find('.district-name').text(obj.name);
    //                 container.append(item);
    //             })
    //         }
    //     },
    //     error: function (error) {
    //     }
    // })

  });
  //hiển thị list quận huyện theo tỉnh thành không có
  $("#district, .ion-ios-arrow-down").click(function () {
    var province = $("#province").find('.toggle-label').attr('data-id');
    //trường hợp chưa chọn tỉnh thành thì hiện thông báo hãy chọn tỉnh thành
    if (province == undefined || province == null) {
        $('.no-province').css('display', 'block');
    }
  });
  //lọc theo district
  $(document).on('click', '.district-item', function () {
    var id = $(this).find('a').data('id');
    var slug = $(this).find('a').data('slug');
    var name = $(this).find('a').text();
    $('#locationState').find('.id_city').val(id);
    $('#locationState').find('.name-state').val(slug);
    if(id >0) {
      $(this).parents('#locationState').find('.toggle-label').text(name);
    }
      // var count = $('.district-list').find(".district-value:checked").length;
      
      // if (count > 0) {
      //     $('.filter-count-district').text('(' + count + ')');
      //     $('.district-filter').css('display', '');
      // } else {
      //     $('.district-filter').css('display', 'none');
      // }
      // var district = [];
			// $(".district-list .district-value").each(function () {
      //   if ($(this).is(':checked')) {
      //     district.push(parseInt($(this).val()));
      //   }
      // })
      // if(district.length >0) {
      //   $(this).parents('#locationState').find('.id_estate').val(JSON.stringify(district))
      // }
        
  })

  //lọc theo Loại Tin
  $('#typecate').click(function () {
    if($('.post-type-list div').length === 0){ console.error(json.typePost);
      $.each(json.typePost, function (_key, _data) {
          $('.post-type-list').append(`<li class="post-type-item"  data-id="${_data.cid}">
          <a href="javascript:void(0)" class="single-filter-area__link">
            <div class="area-title">${_data.cat_title}</div>
            <div class="area-count"></div>
          </a>
      </li>`);
      // .append(`<div class="single-filter-property">
      //     <label class="c-option post-type-item">
      //        <input type="checkbox" class="c-option__input post-type-value" value="${_data.cid}">
      //        <div class="c-option__icon"></div>
      //        <div class="c-option__label">${_data.cat_title}</div>
      //     </label>
      //  </div>`);
      });
    }
  })
  //lọc theo price
  $(document).on('click', '.price-item', function () {
    var id = $(this).find('div').data('id');
    var name = $(this).find('div').text();
    $('#itemFillterPrice').find('#price_fillter').val(id);
    if(id >0) {
      $(this).parents('#itemFillterPrice').find('.toggle-label').text(name);
    }
  })
  $(document).on('click', '.dtich-item', function () {
    var id = $(this).find('div').data('id');
    var name = $(this).find('div').text();
    $('#itemFillterDTich').find('#dtich_fillter').val(id);
    if(id >0) {
      $(this).parents('#itemFillterDTich').find('.toggle-label').text(name);
    }
  })
  $(document).on('click', '.post-type-item', function () {
      // remove active class on all nav links
      $('.nav-type-post').removeClass("active");
      var cidSelect = $(this).data('id');
      var cidName =   $(this).text();
      $('#cid_fillter').val(cidSelect);
      $('#typecate div.toggle-label').text(cidName);
      // var count = $('.post-type-list').find(".post-type-value:checked").length;
      // if (count > 0) {
      //     $('.filter-count-type').text('(' + count + ')');
      //     $('.type-filter').css('display', '');
      // } else {
      //     $('.type-filter').css('display', 'none');
      // }
  })

  //lọc theo Tiện ích
  $(document).on('click', '.post-amenities-item', function () {
      var count = $('.post-amenities-list').find(".post-amenities-value:checked").length;
      if (count > 0) {
          $('.filter-count-amentities').text('(' + count + ')');
          $('.amenities-filter').css('display', '');
      } else {
          $('.amenities-filter').css('display', 'none');
      }
  })


  //lọc theo Khoảng giá
  $(document).on('click', '.post-price-item', function () {
      //kiểm tra checked nếu check thì remove cái khác đi
      var count = $('.post-price-list').find(".post-price-value:checked").length;
      if (count > 0) {
          $('.filter-count-price').text('(' + count + ')');
          $('.price-filter').css('display', '');
      } else {
          $('.price-filter').css('display', 'none');
      }
  })

  $('.dropdown-menu--sP').on('hidden.bs.dropdown', function () {
      getPostList()
  })
  $('form#frm_search_fulltext').submit(function (e) {
    e.preventDefault(); 
    url_search();
    return false;
  });

  ///////HỦY TÌM KIẾM BEGIN
  //hủy search
  $('.filter-search__delete').click(function () {
      $('.search-input').val('');
      $('.search-filter').css('display', 'none')
      getPostList();
  })
  //hủy quận huyện
  $('.filter-district__delete').click(function () {
      $(".district-value").each(function () {
          this.checked = false;
      })
      $('.district-filter').css('display', 'none')
      getPostList();
  })
  //hủy loại tin
  $('.filter-type__delete').click(function () {
      $('.nav-type-post').removeClass("active");
      $(".post-type-value").each(function () {
          this.checked = false;
      })
      $('.type-filter').css('display', 'none')
      getPostList();
  })
  //hủy tiện ích
  $('.filter-amenities__delete').click(function () {
      $(".post-amenities-value").each(function () {
          this.checked = false;
      })
      $('.amenities-filter').css('display', 'none')
      getPostList();
  })
  //hủy khoảng giá
  $('.filter-rangeprice__delete').click(function () {
      $(".post-price-value").each(function () {
          this.checked = false;
      })
      $('.price-filter').css('display', 'none')
      getPostList();
  })

  /////////HỦY TÌM KIẾM END
    // $('#dl-menu').dlmenu();
    // $("li.dropdown, li.dropdown .dropdown-menu").hover(function(){
    //     $(this).find('.dropdown-menu').addClass('fadeInUp').addClass('animated');
    // });
    // jQuery(window).on('resize',function(){
    //     //offset_menu();
    //     fixed_header();
    //    // rep_menu();
    // });
    $('body').on('click', function (e) {
      // if (!$('.list-filters .dropdown').is(e.target) 
      //     && $('.list-filters .dropdown').has(e.target).length === 0 
      //     && $('.open').has(e.target).length === 0
      // ) {
      //     $('.list-filters .dropdown').removeClass('open');
      // }
      //e.stopPropagation();
    });
    // $('.dropdown-menu >*').on('click', function (event) {
    //   $(this).closest('div.dropdown--filter-properties').toggleClass('open');
    // });
    // prevent dropdown menu close while clicking inside
    $(document).on('click', '.dropdown-menu--sP', function (e) {
      e.stopPropagation();
    });
    $(window).scroll(function(){
      if ($(this).scrollTop() > 400) {
          $('.scrollToTop').fadeIn();
        } else {
          $('.scrollToTop').fadeOut();
        }
    });

    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},500);
        return false;
    });

    if($('.btn_copy_link2').length >0) {
      $(".btn_copy_link2").click(function(){   
        $("#article_copy_link_input").select();
        document.execCommand("Copy");
      });
    }
    var pathname = window.location.pathname;
    if(pathname.length>2) {
      // $('.main-nav li a').removeClass('active');
      // $('.main-nav li').each(function( index ) {
      //   var alias = `${$(this).find('a').attr('href')}/`;
      //   pathname = `${pathname}/`
      //   if(alias.indexOf(pathname) >=0) {
      //     $(this).find('a').addClass('active');
      //   }
      //   if(alias.indexOf(`${aliascate}/`) >=0 && aliascate.length >5) {
      //     $(this).find('a').addClass('active');
      //   }
      // })
      // $('.main-nav li .dropdown-menu li').each(function( index ) {
      //   var alias = `${$(this).find('a').attr('href')}__`;
      //   if(alias.indexOf(pathname) >=0) {
      //     $(this).closest('.menu-item-has-children').addClass('active').find('a').addClass('active');
      //   }
      // })
    } else {
      $('.main-nav li').each(function( index ) {
      })
    }
    
    jQuery(window).on('scroll', function () {
      var st = $(window).scrollTop();
      if ($('.nav-top').length > 0) {
        if ($(window).width() > 1200) {
          var ht = $('#nav_bar_header').height()+$('.nav-top').innerHeight();//+$('.nav-top').innerHeight() $('.nav-top').innerHeight()/2; //$('#nav_bar_header').height()+
          if (st > ht) {
            $('.nav-top').addClass('fixtop');
            $('.vip-top').css("margin-top",ht+100);
          } else {
            $('.nav-top').removeClass('fixtop');
            $('.vip-top').css("margin-top",0);
            //$('.vip-top').addClass("mtop");
          }
        } else {
          $('.nav-top').removeClass('fixtop');
        }
      }
      if($('#PanelAreaFillter').length > 0) {
        if ($(window).width() > 1200) {
          var ht = $('#PanelAreaFillter').height(); 
          if (st > (ht+100)) {
            $('#PanelAreaFillter').addClass('fixtop');
          } else {
            $('#PanelAreaFillter').removeClass('fixtop');
          }
        } else {
          $('#PanelAreaFillter').removeClass('fixtop');
        }
      }
    })
    
    // $('.fillter_search').select2({
    //     placeholder: 'Chọn địa điểm',
    //     templateResult: function (data, container) {
    //         if (data.element) {
    //         $(container).addClass($(data.element).attr("class"));
    //         }
    //         return data.text;
    //     }
    // })
    if($('.date-fly').length >0 ) {
      $('.date-fly').datetimepicker({
          weekStart: 1,
          todayBtn:  1,
          autoclose: 1,
          todayHighlight: 1,
          startView: 2,
          minView: 2,
          format: "dd-mm-yyyy"
      });
    }
    
    // $("#slides").owlCarousel({
    // 	autoplay: true,
    //     autoWidth: true,
    //     autoHeight: true,
    //     items: 1,
    //     dots: false,
    //     nav: true,
    //     navText:['<img alt="" src="'+url_site+'static/images/slide-arrow-left.png"/>','<img alt="" src="'+url_site+'static/images/slide-arrow-right.png"/>'],
    //     navClass: [ 'slide-prev', 'slide-next' ],
    //     loop: true,
    //     lazyLoad: true
    // });
    if($(".slide-vip1").length > 0 && window.screen.width > 1024) {
        var isMulti = ($('.slide-vip .owl-carousel .item').length > 1) ? true : false

        $(".slide-vip").owlCarousel({
            autoplay: true,
            items: 1,
            dots: false,
            nav: true,
            navText:['<img alt="" src="'+url_site+'static/images/slide-arrow-left.png"/>','<img alt="" src="'+url_site+'static/images/slide-arrow-right.png"/>'],
            navClass: [ 'slide-prev', 'slide-next' ],
            loop: isMulti,
            lazyLoad: true
        });
    }
    if($("#slides-product").length > 0) {
        var isMulti = ($('#slides-product .owl-carousel .item').length > 1) ? true : false
        $("#slides-product").owlCarousel({
            autoplay: true,
            // autoWidth: true,
            // autoHeight: true,
            items: 1,
            dots: false,
            nav: true,
            navText:['<img alt="" src="'+url_site+'static/images/slide-arrow-left.png"/>','<img alt="" src="'+url_site+'static/images/slide-arrow-right.png"/>'],
            navClass: [ 'slide-prev', 'slide-next' ],
            loop: isMulti,
            lazyLoad: true
        });
    }
    // $("#slidesduan").owlCarousel({
    //     autoplay: false,
    //     autoWidth: false,
    //     autoHeight: true,
    //     items: 1,
    //     dots: false,
    //     nav: true,
    //     navText:['<img alt="" src="images/slide-arrow-left.png"/>','<img alt="" src="images/slide-arrow-right.png"/>'],
    //     navClass: [ 'owl-prev', 'owl-next' ],
    //     loop: true,
    //     lazyLoad: true
    // });

    // $("#news-slides").owlCarousel({
    //     autoplay: true,
    //     autoWidth: false,
    //     autoHeight: true,
    //     dots: false,
    //     nav: false,
    //     loop: true,
    //     lazyLoad: true,
    //     margin: 20,
    //     responsive: {
    //             360: {items:1},
    //             640: {items: 2},
    //             768: {items: 3}
    //         }
    //     });
    // var news_slide = $("#news-slides").data('owlCarousel');
    // $('.nl-slide-left').on('click', function(){
    //     news_slide.prev();
    // });
    // $('.nl-slide-right').on('click', function(){
    //     news_slide.next();
    // });

    // $("#banking-slides").owlCarousel({
    //     autoplay: false,
    //     autoWidth: false,
    //     autoHeight: true,
    //     dots: false,
    //     nav: false,
    //     loop: true,
    //     lazyLoad: true,
    //     margin: 0,
    //     responsive: {
    //             320: {items:1},
    //             360: {items:2},
    //             520: {items:3},
    //             640: {items: 4},
    //             768: {items: 5}
    //         }
    //     });
    
    // $('#depAirport, #arvAirport').on('focus', function(e){
    //     $('#listCity').modal('show');
    // });
});
function resetSubmmit(btn){ 
    btn.button('reset');
    btn.prop("disabled", false);
}
function disabledButton(btn){ 
   btn.button("loading");
    btn.prop('disabled', false);
}
function validateCheckEmail(email) {
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
            
   if( !emailReg.test( email )  || email=="") {
        return false;       
   }
}
function callNotifi(msg,type,title){ 
$.notify({
    title: `<strong>${title}</strong>`,
    message: msg
},{
    delay: 15000,
    placement: {
        from: "top",
        align: "right"
    },
    type: type
});
}
function formatMoney(value){ 
    var Temp = value.split(',');
    Temp = parseInt(Temp.join('')); 
    $('#amount').val(Temp);
    var letformat = Temp.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    $('#amountinput').val(letformat);
  }
function phoneNumber(phone) {
    var rex = /^\+?[0-9]{9,12}$/;
    if (phone.match(rex)) {
        return true;
    } else {
        return false;
    }
}
function checkPriceItem(price,thisPrice, is_null = false){
    if(price ==='' && is_null == false){
        thisPrice.addClass('error');
        return 1;
    }else if(price !== null && price !==''){
        if(validatePrice(price) === false){
          thisPrice.addClass('error');
          return 2;
        }
    }else
     return 0;
}
function validatePrice(value) {
    var isValidMoney = /^\d{0,1111}(\.\d{0,2})?$/.test(value);
    return  isValidMoney;
}


function dateFormat(value,typeFormat = 'year') {
    var check = false;
    var re = /^\d{1,2}\-\d{1,2}\-\d{4}$/;
    if(typeFormat === 'year'){
        re = /^\d{4}\-\d{1,2}\-\d{1,2}$/;
    }
        if( re.test(value)){
            var adata = value.split('-');
            var dd = parseInt(adata[0],10);
            var mm = parseInt(adata[1],10);
            var yyyy = parseInt(adata[2],10);

            if(typeFormat === 'year'){
                dd = parseInt(adata[2],10);
                mm = parseInt(adata[1],10);
                yyyy = parseInt(adata[0],10);
            }
            
            var xdata = new Date(yyyy,mm-1,dd);
            if ( ( xdata.getFullYear() === yyyy ) && ( xdata.getMonth () === mm - 1 ) && ( xdata.getDate() === dd ) ) {
            check = true;
        }
        else {
            check = false;
        }
    } else {
        check = false;
    }
    return  check;
}

function dateFormat(value,typeFormat = 'year') {
  var check = false;
  var re = /^\d{1,2}\-\d{1,2}\-\d{4}$/;
  if(typeFormat === 'year'){
      re = /^\d{4}\-\d{1,2}\-\d{1,2}$/;
  }
      if( re.test(value)){
          var adata = value.split('-');
          var dd = parseInt(adata[0],10);
          var mm = parseInt(adata[1],10);
          var yyyy = parseInt(adata[2],10);

          if(typeFormat === 'year'){
              dd = parseInt(adata[2],10);
              mm = parseInt(adata[1],10);
              yyyy = parseInt(adata[0],10);
          }
          
          var xdata = new Date(yyyy,mm-1,dd);
          if ( ( xdata.getFullYear() === yyyy ) && ( xdata.getMonth () === mm - 1 ) && ( xdata.getDate() === dd ) ) {
          check = true;
      }
      else {
          check = false;
      }
  } else {
      check = false;
  }
  return  check;
}
function getPostList() {

}
function url_search() {
var paramas = [];
var querySearch = [];
if ($('.list-filters .name_provice')) {
  var name_provice = $('.list-filters .name_provice').val();
  if (!isEmpty(name_provice)) {
    console.error('name_provice', name_provice);
    paramas.push(name_provice);
  }
}
if ($('.list-filters .name-state')) {
  var name_state = $('.list-filters .name-state').val();
  if (!isEmpty(name_state)) {
    console.error('name_state', name_state);
    paramas.push(name_state);
  }
}
if ($('.list-filters #cid_name_fillter')) {
  var cid_name_fillter = $('.list-filters #cid_name_fillter').val();
  if (!isEmpty(cid_name_fillter)) {
    paramas.push(cid_name_fillter);
  }
}
if ($('.list-filters #price_fillter')) {
  var price_fillter = $('.list-filters #price_fillter').val();
  if (!isEmpty(price_fillter)) {
    querySearch.push(`price=${price_fillter}`);
  }
}
if ($('.list-filters #dtich_fillter')) {
  var dtich_fillter = $('.list-filters #dtich_fillter').val();
  if (!isEmpty(dtich_fillter)) {
    querySearch.push(`dtich=${dtich_fillter}`);
  }
}
var sQuery = '';
if (querySearch.length) {
  sQuery = `?${querySearch.join('&')}`;
}
console.error(sQuery)
if (paramas.length) { 
  location.href=`${url_site}${paramas.join('/')}${sQuery}`;
}
}
function lessMore() {
var dots = document.getElementById("less_more");
var moreText = document.getElementById("less_more");
var btnText = document.getElementById("lessMore");
if (dots.style.height === "200px") {
  $('.detail_page_list').css('height','100%');
  btnText.innerHTML = "Đóng lại <i class=\"fa fa-angle-up bold font18\" aria-hidden=\"true\"></i>";
  //moreText.style.display = "none";
  
} else {
  $('.detail_page_list').css('height','200px');
  // dots.style.display = "none";
  btnText.innerHTML = "Đọc thêm <i class=\"fa fa-angle-down bold font18\" aria-hidden=\"true\"></i>";
  // moreText.style.display = "inline";
}
}
function isEmpty  (obj) {
return typeof obj === 'string' && !obj.trim() || typeof obj === 'undefined' || obj === null || (typeof obj === 'object' && Object.keys(obj).length === 0 && !(obj instanceof Date) );
}