var resize_timer;
var call_timer;
var domain;
var list_title = "";
var sell_price = [0,2000,3000,4000,5000,6000,7000,8000,9000,10000,15000,20000,25000,30000,40000,50000,60000,70000,80000,90000,100000,110000,120000,130000,140000,150000];
var sell_price_max = 150000;
var deposit_price = [0,1000,2000,3000,5000,10000,20000,30000];
var deposit_price_max = 30000;
var rent_price = [0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,250,300,350,400,450,500];
var rent_price_max = 500;
var area = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40];
var area_max = 40;
var area_total = [0,50,100,200,300,400,500,600,700,800,900,1000];
var area_total_max = 1000;
var area_land = [0,50,100,200,300,400,500,600,700,800,900,1000];
var area_land_max = 1000;
$(document).ready(function(){ 
	lat = $("#form input[name='lat']").val();
	lng = $("#form input[name='lng']").val();
	level = $("#form input[name='level']").val();
	domain = $("#form input[name='domain']").val();
	mapdraw_event();
	$("#form").change(function(){
		mapdraw_event();
	});
		$('.dropdown-menu').click(function(e) {
		e.stopPropagation();
	});
	init_rangeslider();
	/***********************************************
	 * 초기화 버튼 실행
	 ***********************************************/
	$(".btn-init").click(function(){
		$(this).parent().parent().parent().find("input:checkbox").each(function(){
			$(this).prop("checked", false);
		});
		$(this).parent().parent().parent().find("input:radio").each(function(){
			$(this).prop("checked", false);
		});
		$(this).parent().parent().parent().find("select").each(function(){
			$(this).val("");
		});
		mapdraw_event();
	});
	$(".btn-init-price").click(function(){
		sell_price_range.reset();
		deposit_price_range.reset();
		rent_price_range.reset();
		mapdraw_event();
	});
	$(".btn-init-area").click(function(){
		if($("#area").length>0) area_range.reset();
		if($("#area_total").length>0) area_total_range.reset();
		if($("#area_land").length>0) area_land_range.reset();
		mapdraw_event();
	});
	$(".btn-init-option").click(function(){
		$("#form").find("select").each(function(){
			$(this).val("");
		});
		mapdraw_event();
	});
	$("#sorting").change(function(){
		mapdraw_event();
	});
	if($("#keyword").length > 0){
		$("#keyword").autocomplete({
			selectFirst: false, 
			autoFill: false,
			autoFocus: false,
			focus: function(event,ui){
				return false;
			},
			delay: 0,
			scrollHeight:40,
			minLength:2,
			select: function(a,b){
				
				$("#form input[name='lat']").val(b.item.lat);
				$("#form input[name='lng']").val(b.item.lng);
				$("#sorting").val("distance_asc");
				get_map_list(0);
				
				a.stopPropagation();
				return false;
			},
			source: function(request, response){
				totalSearch(lat,lng, response);
			},
		}).data("ui-autocomplete")._renderItem = autoCompleteRenderSearch;
	}
});
function totalSearch(lat,lng, response){
	//숫자일 경우에는 매물검색으로 인식해서 해당 매물번호로 이동되므로 아무 것도 하지 않는다.
	if($.isNumeric($("#search").val())){
		return;		
	} else {
		$.ajax({
			url: "/search/address",
			type: "POST",
			data: {
				keyword : $("#keyword").val(),
			},
			dataType: "json",
			success: function(data) {
				if(data!=""){
					response( $.map( data, function( item ) {
						return {
							id: item.id,
							title: item.title,
							type: item.type,
							lat: item.lat,
							lng: item.lng
						}; 
					}));			
				}
			}
		});
	}
}
function autoCompleteRenderSearch(ul, item) {
	return $("
").data("item.autocomplete", item).append(' '+item.title).appendTo(ul);	
}
function mapdraw_event(){
	list_title 	= "";
	filter_title();		/* 검색버튼 타이틀 수정 */
	// 2023-08-18 바로 호출하면 가격을 못가져오는 현상이 있음
	setTimeout(function() { 
		get_map_list(0);	/* 지도 매물 리스트 */
	 }, 450);
}
function get_map_list(page){
	
	var total = 0;
	var formData = $("#form").serialize();
	formData+='&sorting='+$("#sorting").val();
	formData+='&method=grid';
console.log(formData);
	$.ajax({
		type	: "POST",
		url		: "/property/ajax_grid/"+page,
		data 	: formData,
		dataType: 'json',
		success: function(data) {
			$.each(data, function(key, val) {
				
				if(key=="result") {
					$("#property_list").html(val);
				}
				if(key=="pagination") {
					$("#pagination").html(val);
					get_map_list_paging();
				}
						
				if(key=="total"){
					total = val;
					$("#map_label").html("매물 " + total + "개");	
				}
			});
			$("#property_list").animate({
				scrollTop: 0
			}, 600);
			if(total=="0") {
				$("#property_list").html("매물이 없습니다.
지도를 옮기거나 검색조건을 변경해 보세요.
");
			} 
			$(".property-zzim span").click(function(event){
				event.stopPropagation();
				event.preventDefault();
			});
			init_zzim();
		}
	});
}
function get_map_list_paging(){
	$(".page-link").click(function(e){
		e.preventDefault();
		var page = $(this).attr("href").substring($(this).attr("href").lastIndexOf('/') + 1)
		get_map_list(page);
		
		$(".property_list_wrapper").animate({
			scrollTop: 0
		}, 600);
	});
}
//다른대서도 사용
function init_zzim(){
	$(".property-zzim span").click(function(){
					if(confirm("로그인하시겠습니까?")){
				location.href="/member/signin";
			}
				
	});
}
function init_filter(){
	$("#form").find("input:checkbox").each(function(){
		$(this).prop("checked", false);
	});
	$("#form").find("select").each(function(){
		$(this).val("");
	});
	
	sell_price_range.reset();
	deposit_price_range.reset();
	rent_price_range.reset();
	if($("#area").length>0) area_range.reset();
	if($("#area_total").length>0) area_total_range.reset();
	if($("#area_land").length>0) area_land_range.reset();
	mapdraw_event();
}
function filter_title(){
	$("#selltype_label").html("거래 방식");
	$("#cate_label").html("매물 종류");
	$("#bedcnt_label").html("방 수");
	$("#theme_label").html("테마");
	$("#price_label").html("가격 대");
	$("#area_label").html("면적");
	$("#option_label").html(" 상세 검색");
	var title = "";
	var btn = ['selltype','cate','bedcnt','theme'];
	$.each(btn,function(index,item){
		title = "";
		$("#"+item+"_group input").each(function(){
			if($(this).is(":checked")){
				if(title=="") title = title + $(this).data("title");
				else if(title!="") title = title + "," + $(this).data("title");
			}
		});
		if(title!="") {
			$("#"+item+"_label").removeClass("btn-outline-secondary");
			$("#"+item+"_label").addClass("btn-secondary");
			$("#"+item+"_label").html(title);
		} else {
			$("#"+item+"_label").removeClass("btn-secondary");
			$("#"+item+"_label").addClass("btn-outline-secondary");
		}
	});
	/* 
		가격대 
		- 앞 숫자, 뒷 숫자 모두 보여준다.
		- labeling_sell_price
		- labeling_deposit_price
		- labeling_rent_price
	*/
	title = "";
	var sell_price		= $("#sell_price").val();
	var deposit_price	= $("#deposit_price").val();
	var rent_price		= $("#rent_price").val();
	
	if(sell_price!=";" && sell_price!="null;null" && sell_price!="0;"+sell_price_max) {
		title = filter_title_price($("#sell_price").val(),"sell");
	}
	if(deposit_price!=";" && deposit_price!="null;null" && deposit_price!="0;"+deposit_price_max) {
		title = filter_title_price($("#deposit_price").val(),"deposit");
	}
	if(rent_price!=";" && rent_price!="null;null" && rent_price!="0;"+rent_price_max) {
		title = title + filter_title_price($("#rent_price").val(),"rent");
	}
	if(title.trim()!="") {
		$("#price_label").removeClass("btn-outline-secondary");
		$("#price_label").addClass("btn-secondary");
		$("#price_label").html(title);
	} else {
		$("#price_label").removeClass("btn-secondary");
		$("#price_label").addClass("btn-outline-secondary");
	}	
	/**
	 * 면적
	 */
	title = "";
    var area		    = $("#area").val();
	var area_total	    = $("#area_total").val();
	var area_land		= $("#area_land").val();
    
	if($("#area").length>0){
		var area = $("#area").val();
		
		if(area!="null;null" && area!="0;"+area_max) {
			title = filter_title_area($("#area").val());
		}
	}
	
	if(title.trim()!="") {
		$("#area_label").removeClass("btn-outline-secondary");
		$("#area_label").addClass("btn-secondary");
		$("#area_label").html(title);
	} else {
		$("#area_label").removeClass("btn-secondary");
		$("#area_label").addClass("btn-outline-secondary");
	}	
	
	/* 옵션 */
	//floor, build_date
	title="";
	if($("#form select[name='floor'] option:selected").val()!="") {
		title = $("#form select[name='floor'] option:selected").text()+" ";
	}
	
	if($("#form select[name='build_date'] option:selected").val()!=""){
		title = title + $("#form select[name='build_date'] option:selected").text();
	}
	if($("#form select[name='elevator'] option:selected").val()!=""){
		title = title + $("#form select[name='elevator'] option:selected").text();
	}
	if($("#form select[name='park'] option:selected").val()!=""){
		title = title + $("#form select[name='park'] option:selected").text();
	}
	if($("#form select[name='status_id'] option:selected").val()!=""){
		title = title + $("#form select[name='status_id'] option:selected").text();
	}
	if(title.trim()!="") {
		$("#option_label").removeClass("btn-outline-secondary");
		$("#option_label").addClass("btn-secondary");
		$("#option_label").html(title);
	} else {
		$("#option_label").removeClass("btn-secondary");
		$("#option_label").addClass("btn-outline-secondary");
	}	
}
function filter_title_price(ts,gubun){
	var r = "";
	var t = ts.split(';');
	
	
	if(gubun=="sell"){
		/* 주가격 */
		if(t[0]!="null" && t[0]!="0") r = r+labeling_sell_price(t[0]);
		if(t[1]!="null") r = r+"~"+labeling_sell_price(t[1]);
		return r;
	
	} else if(gubun=="deposit"){
		/* 주가격 */
		if(t[0]!="null" && t[0]!="0") r = r+labeling_deposit_price(t[0]);
		if(t[1]!="null") r = r+"~"+labeling_deposit_price(t[1]);
		return r;
	} else {
		/* 보조 가격 */
		if(t[0]!="null" && t[0]!="0") r = r+labeling_rent_price(t[0]);
		if(t[1]!="null") r = r+"~"+labeling_rent_price(t[1]);
		if(r!="") return ",월"+r;
	}
	
	
}
function filter_title_area(ts){
	var r = "";
	var t = ts.split(';');
	/* 주가격 */
	if(t[0]!="null" && t[0]!="0") r = r+t[0]+"평";
	if(t[1]!="null" && t[1]!=area_max) r = r+"~"+t[1]+"평";
	return r;
	
}
function filter_title_area_total(ts){
	var r = "";
	var t = ts.split(';');
	/* 주가격 */
	if(t[0]!="null" && t[0]!="0") r = r+t[0]+"평";
	if(t[1]!="null" && t[1]!=area_total_max) r = r+"~"+t[1]+"평";
	return r;
	
}
function filter_title_area_land(ts){
	var r = "";
	var t = ts.split(';');
	/* 주가격 */
	if(t[0]!="null" && t[0]!="0") r = r+t[0]+"평";
	if(t[1]!="null" && t[1]!=area_land_max) r = r+"~"+t[1]+"평";
	return r;
	
}
function init_rangeslider(){
	$("#sell_price").ionRangeSlider({
	  type: 'double',
	  min: 0,
	  max: sell_price_max,
	  from: 0,
	  to: sell_price_max,
	  values: sell_price,
	  grid: false,
	  grid_num:1000,
	  grid_snap: true,
	  skin: 'round',
	  prettify: labeling_sell_price,
	});
	
	sell_price_range = $("#sell_price").data("ionRangeSlider");
	if($("#form input[name='sell_from']").val()!="" || $("#form input[name='sell_to']").val()!=""){
        if (typeof sell_price_range === "undefined" || typeof sell_price_range.update === "undefined") {
        }else{
            sell_price_range.update({
                from: sell_price.indexOf(Number($("#form input[name='sell_from']").val())),
                to: sell_price.indexOf(Number($("#form input[name='sell_to']").val()))
            });
            
        }
    }
	$("#deposit_price").ionRangeSlider({
	  type: 'double',
	  min: 0,
	  max: deposit_price_max,
	  from: 0,
	  to: deposit_price_max,
	  values: deposit_price,
	  grid: false,
	  grid_num:1000,
	  grid_snap: true,
	  skin: 'round',
	  prettify: labeling_deposit_price,
	});
	
	deposit_price_range = $("#deposit_price").data("ionRangeSlider");
    if($("#form input[name='deposit_from']").val()!="" || $("#form input[name='deposit_to']").val()!=""){
        if (typeof deposit_price_range === "undefined" || typeof deposit_price_range.update === "undefined") {
        }else{
            
            deposit_price_range.update({
                from: deposit_price.indexOf(Number($("#form input[name='deposit_from']").val())),
                to: deposit_price.indexOf(Number($("#form input[name='deposit_to']").val()))
            });
        }
    }
	$("#rent_price").ionRangeSlider({
	  type: 'double',
	  min: 0,
	  max: rent_price_max,
	  from: 0,
	  to: rent_price_max,
	  values: rent_price,
	  grid: false,
	  grid_snap: true,
	  skin: 'round',
	  prettify: labeling_rent_price
	});
	
	rent_price_range = $("#rent_price").data("ionRangeSlider");
    if($("#form input[name='rent_from']").val()!="" || $("#form input[name='rent_to']").val()!=""){
        if (typeof rent_price_range === "undefined" || typeof rent_price_range.update === "undefined") {
        }else{
            rent_price_range.update({
                from: rent_price.indexOf(Number($("#form input[name='rent_from']").val())),
                to: rent_price.indexOf(Number($("#form input[name='rent_to']").val()))
            });
            
        }
    }
	if($("#area").length>0){
		$("#area").ionRangeSlider({
		  type: 'double',
		  min: 0,
		  max: area_max,
		  from: 0,
		  to: area_max,
		  values: area,
		  grid: false,
		  grid_snap: true,
		  skin: 'round',
		  prettify: labeling_area
		});
		area_range			= $("#area").data("ionRangeSlider");
	}
    if($("#form input[name='area_from']").val()!="" || $("#form input[name='area_to']").val()!=""){
        if (typeof area_range === "undefined" || typeof area_range.update === "undefined") {
        }else{
            area_range.update({
                from: area.indexOf(Number($("#form input[name='area_from']").val())),
                to: area.indexOf(Number($("#form input[name='area_to']").val()))
            });
        }
    
    }
	if($("#area_total").length>0){
		$("#area_total").ionRangeSlider({
		  type: 'double',
		  min: 0,
		  max: area_total_max,
		  from: 0,
		  to: area_total_max,
		  values: area_total,
		  grid: false,
		  grid_snap: true,
		  skin: 'round',
		  prettify: labeling_area_total
		});
        area_total_range	= $("#area_total").data("ionRangeSlider");
        
	}
    if($("#form input[name='area_total_from']").val()!="" || $("#form input[name='area_total_to']").val()!=""){
        if (typeof area_total_range === "undefined" || typeof area_total_range.update === "undefined") {
        }else{
            area_total_range.update({
                from: area_total.indexOf(Number($("#form input[name='area_total_from']").val())),
                to: area_total.indexOf(Number($("#form input[name='area_total_to']").val()))
            });
            
        }
    }
	if($("#area_land").length>0){
		$("#area_land").ionRangeSlider({
		  type: 'double',
		  min: 0,
		  max: area_land_max,
		  from: 0,
		  to: area_land_max,
		  values: area_land,
		  grid: false,
		  grid_snap: true,
		  skin: 'round',
		  prettify: labeling_area_land
		});
		area_land_range		= $("#area_land").data("ionRangeSlider");
	}
    if($("#form input[name='area_land_from']").val()!="" || $("#form input[name='area_land_to']").val()!=""){
        if (typeof area_land_range === "undefined" || typeof area_land_range.update === "undefined") {
        }else{
            area_land_range.update({
                from: area_land.indexOf(Number($("#form input[name='area_land_from']").val())),
                to: area_land.indexOf(Number($("#form input[name='area_land_to']").val()))
            });
        }
    }
	filter_title();
}
function labeling_sell_price(ts) {
	if(ts == 0) {
		return "0원"
	} else if(ts >= sell_price_max) return "제한없음";
	else return numberToKorean(ts) + "원";
}
function labeling_deposit_price(ts) {
	if(ts == 0) {
		return "0원"
	} else if(ts >= deposit_price_max) return "제한없음";
	else return numberToKorean(ts) + "원";
}
/**
 * 월세 가격 검색 보여주기
 */
function labeling_rent_price(ts) {
	if(ts == 0) {
		return "0원"
	} else if(ts >= rent_price_max) return "제한없음";
	else return numberToKorean(ts) + "원";
}
/**
 * 면적 검색 보여주기
 */
function labeling_area(ts) {
	if(ts >= area_max) return "제한없음";
	else return ts + "평";
}
function labeling_area_total(ts) {
	if(ts >= area_total_max) return "제한없음";
	else return ts + "평";
}
function labeling_area_land(ts) {
	if(ts >= area_land_max) return "제한없음";
	else return ts + "평";
}
function numberToKorean(number){
	
	number = number *10000; /* 사이트에서 기본으로 1만원 기준으로 하니까 */
    
    var inputNumber  = number < 0 ? false : number; /* 금액이 0보다 작은 것은 성립하지 않는다 */
    var unitWords    = ['', '만', '억', '조', '경'];
    var splitUnit    = 10000;
    var splitCount   = unitWords.length;
    var resultArray  = [];
    var resultString = '';
    for (var i = 0; i < splitCount; i++){
        var unitResult = (inputNumber % Math.pow(splitUnit, i + 1)) / Math.pow(splitUnit, i);
        unitResult = Math.floor(unitResult);
        if(unitResult>=1000){
        	resultArray[i] = unitResult/1000 + "천";
        } else if (unitResult >= 100){
        	resultArray[i] = unitResult/100 + "백";
        } else if (unitResult > 0){
            resultArray[i] = unitResult;
        } 
    }
    for (var i = 0; i < resultArray.length; i++){
        if(!resultArray[i]) continue;
        resultString = String(resultArray[i]) + unitWords[i] + resultString;
    }
    return resultString;
}