var map;
var marker = null;
var markers = [];
var markers_circle = [];
var smarkers = []; //지하철 삭제를 위해서 필요
var sido_markers = [];
var gugun_markers = [];
var dong_markers = [];
var danzi_markers = [];
var init_lat;
var init_lng;
var init_zoom;
var idle_disable=0;
var maxzoom;
var resize_timer; //resize를 처리하기 위한 타이머
var call_timer; //resize를 처리하기 위한 타이머
var map_click = true; //구군이나 동 클러스터를 클릭했을 경우 right_close()를 실행시키지 않기 위한 변수
var right_exists = false; //우측 검색결과 목록이 있을 경우에는 지도를 이동,확대시 목록을 재호출하지 않기 위한 변수
var click_cluster = false; //매물 클러스터에 클릭이 되어 있는지 여부를 체크하여 지도를 이동,확대시 상태값을 유지하기 위한 변수
var currentTypeId; //현재 지도 타입을 저장
var infowindow; //단지 인포윈도우
is_cluster='';//검색추가
/*****************************************************
* ie버젼체크
*****************************************************/
function getInternetExplorerVersion() {    
     var rv = -1; // Return value assumes failure.    
     if (navigator.appName == 'Microsoft Internet Explorer') {        
          var ua = navigator.userAgent;        
          var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");        
          if (re.exec(ua) != null)            
              rv = parseFloat(RegExp.$1);    
         }    
     return rv; 
} 
var ie_v=getInternetExplorerVersion();
if(ie_v==9 || ie_v==8){
	styles='style="background:#3d9ecc; color:#fff; border-radius:50%; text-align:center; line-height:70px; width:70px; height:70px; "';
} else {
	styles='';
}
/*****************************************************
* 지도 이벤트 최초 호출
*****************************************************/
function initialize(lat, lng, level,  maxzoom, ml) {
	
	init_lat = lat;
	init_lng = lng;
	init_zoom = level;
	
	maxzoom = maxzoom;
	var mapOptions = {
		center: new daum.maps.LatLng(lat, lng),
		level: level
	};
	
	map = new daum.maps.Map(document.getElementById('map'), mapOptions);
	
	/*** 콘트롤 자체적으로 만들어서 표시
	var mapTypeControl = new daum.maps.MapTypeControl();
	map.addControl(mapTypeControl, daum.maps.ControlPosition.TOPRIGHT);
	var zoomControl = new daum.maps.ZoomControl();
	map.addControl(zoomControl, daum.maps.ControlPosition.RIGHT);
	***/
	daum.maps.event.addListener(map, 'idle', call_map);
	daum.maps.event.addListener(map, 'click', function(mouseEvent) {
		if(map_click){
			right_close();
		}
		map_click = true;
	});
	//다음 지도는 숫자가 작아질 수록 지도가 확대되는 것이므로 maxzoom보다 더 작아지지 않도록 해야 한다.
	daum.maps.event.addListener(map, 'dragend', function() {
				if( maxzoom > map.getLevel() ) {
			map.setLevel(maxzoom);
			$('.toast').stop().fadeIn(400).delay(3000).fadeOut(400);
		}
		  
	});
	daum.maps.event.addListener(map, 'zoom_changed', function() {
		right_close();
				if( maxzoom > map.getLevel() ) {
			map.setLevel(maxzoom);
			$('.toast').stop().fadeIn(400).delay(3000).fadeOut(400);
		}
			});
	$( window ).resize(function() {
		mapsize();
		clearTimeout(resize_timer);
		resize_timer = setTimeout(mapsize, 200);
	});
	
	$(".biz_switch_button").show();
	//콘트롤 버튼 
	var changeMaptype;
	$(".map-btn").click(function(){
		init_contron_btn();
		maptype = $(this).data("type");
	    // 이미 등록된 지도 타입이 있으면 제거합니다
		if (currentTypeId) {
			map.removeOverlayMapTypeId(currentTypeId);    
		}
		if( maptype == "roadview" ) {
			map.setMapTypeId(daum.maps.MapTypeId.ROADMAP);
			changeMaptype = daum.maps.MapTypeId.ROADMAP;
			map.addOverlayMapTypeId(changeMaptype);
			$(this).find("img").attr("src","/assets/common/img/map/map-click-btn.png");
		} else if (maptype === 'sky') {
			map.setMapTypeId(daum.maps.MapTypeId.HYBRID);
			changeMaptype = daum.maps.MapTypeId.SKYVIEW;
			$(this).find("img").attr("src","/assets/common/img/map/satellite-click-btn.png");
		} else if (maptype === 'use_district') {
			changeMaptype = daum.maps.MapTypeId.USE_DISTRICT;
			map.addOverlayMapTypeId(changeMaptype);
			$(this).find("img").attr("src","/assets/common/img/map/register-click-btn.png");
		}		
		
		// 지도에 추가된 타입정보를 갱신합니다
		currentTypeId = changeMaptype;      
	});
}
function init_contron_btn(){
	$(".map-btn").each(function(){
		maptype = $(this).data("type");
		if( maptype == "roadview" ) {
			$(this).find("img").attr("src","/assets/common/img/map/map-btn.png");
		} else if (maptype === 'sky') {
			$(this).find("img").attr("src","/assets/common/img/map/satellite-btn.png");
		} else if (maptype === 'use_district') {
			$(this).find("img").attr("src","/assets/common/img/map/register-btn.png");
		}
	});
}
/** 지도 콘트롤 명령: 줌인 **/
function zoomIn(){
	 map.setLevel(map.getLevel() - 1);
}
/** 지도 콘트롤 명령: 줌아웃 **/
function zoomOut(){
	 map.setLevel(map.getLevel() + 1);
}
function mapsize(){
		var top_size = $(".header").outerHeight()+$(".band-wrapper").outerHeight();
		if($('.pre-header').css('display') != "none")  top_size = top_size + $(".pre-header").outerHeight();
		var all_size = $(window).height();
		$("#map").height(all_size-top_size);
}
/*****************************************************
* 지도의 데이터 가져오기
******************************************************/
function call_map(){
	reset_coord_marker();
	if(map.getCenter().getLat() > 0){
		init_lat = map.getCenter().getLat();
		init_lng = map.getCenter().getLng();
		init_zoom = map.getLevel();
	}
	$("#lat").val(init_lat);
	$("#lng").val(init_lng);
	$("#zoom").val(init_zoom);
	$.ajax({
		url: "/search/set_nowgeo",
		type: "POST",
		data: {
			now_lat : init_lat,
			now_lng : init_lng,
			now_zoom : init_zoom,
		},
		success: function(data){
		}
	});
	
	if(idle_disable==0){ 
		/** 지도 움직임이 뚝뚝 끊겨서 이걸 수정함
		map.setDraggable(false); 
		map.setZoomable(false);
		$('#map').children(':first').css("cursor", "wait");
		**/
		clearTimeout(call_timer);
		call_timer = setTimeout(function(){
			remove_data();
			get_map_data();
			if($("#where_wrapper").hasClass("display-none")){
				right_exists = false;
				if($("#biz_map").length > 0 && $("#biz_map").val()=="1"){
					get_map_list_biz(0);
				}
				else{
					get_map_list(0);
				}
			}
			$("#category-navigation").find("a").css("cursor", "pointer");
		}, 300);
	}
}
/*****************************************************
* 지도상에 있는 모든 마커를 제거한다.
******************************************************/
function remove_data(){
	for (var i = 0; i < smarkers.length; i++) {
		smarkers[i].setMap(null);
	}
	if(smarkers.length>0)	smarkers = [];
	for (var i = 0; i < sido_markers.length; i++) {
		sido_markers[i].setMap(null);
	}
	if(sido_markers.length>0)	sido_markers = [];
	for (var i = 0; i < gugun_markers.length; i++) {
		gugun_markers[i].setMap(null);
	}
	if(gugun_markers.length>0)	gugun_markers = [];
	for (var i = 0; i < dong_markers.length; i++) {
		dong_markers[i].setMap(null);
	}
	if(dong_markers.length>0)	dong_markers = [];
	for (var i = 0; i < danzi_markers.length; i++) {
		danzi_markers[i].setMap(null);
	}
	if(danzi_markers.length>0)	danzi_markers = [];
	for (var i = 0; i < markers_circle.length; i++) {
		if(typeof markers_circle[i] !== 'undefined') markers_circle[i].setMap(null);
	}	
	for (var i = 0; i < markers.length; i++) {
		if(typeof markers[i] !== 'undefined') markers[i].setMap(null);
	}
	if(markers.length>0)	markers = [];
}
/*****************************************************
* 가격을 표시한다.
******************************************************/
function price_text(num){
	if(num >= 10000){
		var str = "" + num/10000; 
		var index = str.indexOf( "." ); 
		price = str.substr( 0, index + 4 ) + "억원";
	} else {
		price = numberWithCommas(num) + "만원";
	}
	
	return price;
}
/*****************************************************
* 지도에 지하철,시,구군,동 단위를 표시한다.
******************************************************/
function get_map_data(){
	
	if(is_cluster=='danzi' ){ //검색추가
		danzi_list(danzi_address_id_val,danzi_name_val);//검색추가
	} else if(is_cluster=='subway' ){ //검색추가
		subway_list(subway_x,subway_y,subway_id,subway_where); //검색추가
	} else if(is_cluster=='dong' ){ //검색추가
		dong_list(dong_address_id,dong_where); //검색추가
	} else if(is_cluster=='cluster' ){ //검색추가
		cluster_list(cluster_count, cluster_x, cluster_y, cluster_ids); //검색추가
	} //검색추가
	
	
	
	var json_url = ($("#biz_map").length > 0 && $("#biz_map").val()=="1") ? "/main/get_json_biz" : "/main/get_json";
	$.ajax({
		type: 'POST',
		url: json_url,
		cache: false,
		data: {'zoom':map.getLevel(),'swlat':map.getBounds().getSouthWest().getLat(), 'nelat':map.getBounds().getNorthEast().getLat(), 'swlng':map.getBounds().getSouthWest().getLng(), 'nelng':map.getBounds().getNorthEast().getLng()},
		dataType: 'json',
		success: function(jsonData){
			$.each(jsonData, function(key, val) {
				
				if(key=="subway"){
											get_subway_map(val);
					
				} else if(key=="marker"){
					if($("#biz_map").length > 0 && $("#biz_map").val()=="1"){
						get_marker_map_biz(val);
					}
					else{
						get_marker_map(val);
					}
					
				} else if(key=="sido"){ //시 클러스터				
					
					get_sido_map(val);
				} else if(key=="gugun"){ //구 클러스터
					
					get_gugun_map(val);
				} else if(key=="dong"){ //동 클러스터
					
					get_dong_map(val);
				} else if(key=="danzi" && map.getLevel()<=5){
					get_danzi_map(val);
				}
			}); /** jsonData foreach end **/
			map.setDraggable(true);
			map.setZoomable(true);
			idle_disable = 0;
		}
	});
}
/*****************************************************
* 지도에 지하철 정보를 표시한다.
* 5보다 작으면 좀 크게 보여주고 아니면 좀 작게 보여준다.
******************************************************/
var subway_change = false;
function get_subway_map(val){
	var subway_id = "";
	var subway_x = "";
	var subway_y = "";
	var where = "";
	$.each(val, function(key1, val1) {
		if(map.getLevel()<=5){
			// 커스텀 오버레이를 생성합니다
			smarkers[key1] = new daum.maps.CustomOverlay({
				map: map,
				position: new daum.maps.LatLng(val1["lat"], val1["lng"]),
				content: "

"+val1["name"]+"
"+val["name"]+"("+val["cnt"]+")"+"
",
			yAnchor: 0.6
		});
		//지하철역을 검색했을 경우 해당 지하철역을 선택해준다
		if($("#search_type").val()=="address" && $("#search_value").val()==val["id"]){
			subway_id = val["id"];
			subway_x = val["lat"];
			subway_y = val["lng"];
			where = val["name"]+" 검색결과("+val["cnt"]+")";
		}
		//통합검색으로 지하철역을 검색했을 경우 해당 지하철역을 선택해준다
		if($("#search_type").val()=="google" && $("#search_value").val()==val["name"]){
			subway_id = val1["id"];
			subway_x = val1["lat"];
			subway_y = val1["lng"];
			where = val["name"]+" 검색결과("+val["cnt"]+")";			
		}
	});
	if($("#right_subway_id").val()!=""){
		subway_cluster_hover($("#right_subway_id").val());
	}
	if(subway_id!="" && !subway_change){
		subway_list("","",subway_id,where);
	}
}
/*****************************************************
* 지도에 시도에 대한 커스텀 오버레이를 생성한다
******************************************************/
function get_sido_map(val){
	$.each(val, function(key, val) {
		sido_markers[key] = new daum.maps.CustomOverlay({
			map: map,
			position: new daum.maps.LatLng(val["lat"], val["lng"]),
			content: ""+val["sido"]+"
",
			yAnchor: 1 
		});
	});
}
/*****************************************************
* 지도에 구군에 대한 커스텀 오버레이를 생성한다
******************************************************/
function get_gugun_map(val){
	$.each(val, function(key, val) {
		gugun_markers[key] = new daum.maps.CustomOverlay({
			map: map,
			position: new daum.maps.LatLng(val["lat"], val["lng"]),
			content: ""+val["gugun"].replace(" ","
")+"("+val["cnt"]+")"+"
",
			yAnchor: 1 
		});
	});
}
/*****************************************************
* 지도에 동에 대한 커스텀 오버레이를 생성한다
******************************************************/
var dong_change = false;
function get_dong_map(val){
	var address_id = "";
	var where = "";
	$.each(val, function(key, val) {
		dong_markers[key] = new daum.maps.CustomOverlay({
			map: map,
			position: new daum.maps.LatLng(val["lat"], val["lng"]),
			content: ""+val["dong"]+"("+val["cnt"]+")"+"
",
			yAnchor: 1 
		});
		//동을 검색했을 경우 해당 동을 선택해준다
		if($("#search_type").val()=="address" && $("#search_value").val()==val["id"]){
			address_id = val["id"];
			where = val["dong"]+" 검색결과("+val["cnt"]+")";
		}
		//통합검색으로 동을 검색했을 경우 해당 동을 선택해준다
		if($("#search_type").val()=="google" && $("#search_value").val()==val["dong"]){
			address_id = val["id"];
			where = val["dong"]+" 검색결과("+val["cnt"]+")";			
		}
	});
	if($("#right_address_id").val()!=0){
		dong_cluster_hover($("#right_address_id").val());
	}
	if((address_id!="" && !dong_change) || ((address_id!=$("#right_address_id").val()) && address_id!=0)){
		dong_list(address_id,where);
	}
}
/*****************************************************
* 지도에 단지에 대한 커스텀 오버레이를 생성한다
******************************************************/
function get_danzi_map(val){
	$.each(val, function(d_key, d_val) {
		var icon_content = '';
			icon_content = '';
			icon_content +='	

';
			icon_content +='
'+d_val["danzi_count"]+'
';
			icon_content +=''+d_val["name"]+'
';
		danzi_markers[d_key] = new daum.maps.CustomOverlay({
			map: map,
			position: new daum.maps.LatLng(d_val["lat"], d_val["lng"]),
			content: icon_content,
			yAnchor: 0
		});
	});
	if($("#danzi_address_id").val()!=0){
		danzi_cluster_hover();
	}
}
function danzi_over(lat,lng,address_id,name,floor,total_house,buildyear,image,count){
	if (typeof image !== 'undefined' && image!='null' && image!='') {
		if ( image.match(/http/)) {
			image = image;
		} else {
			image = image.replace(".", "_thumb.");
			image = "/uploads/danzi/"+image;
		}
	} else {
		image = "/assets/common/img/no_thumb.png";
	}
	
	if(infowindow) infowindow.close();
	var over_content = '';
		over_content += '';
		over_content +='	
';
		over_content += '		

';
		over_content += '	
';
		over_content += '	
';
		over_content += '		
'+name+'
';
		over_content += '		
'+floor+'층 / '+total_house+'세대 / 건축년도 '+buildyear+'
';
		over_content += '		
입주가능한 호수 '+count+'개
';
		over_content += '	
';
		over_content += '
"+activated_icon+price+"
",
					yAnchor: -0.3,
					zIndex: 1
				});							
			}
			markers_circle[key1] = new daum.maps.Marker({
				position: loc,
				image: new daum.maps.MarkerImage(imageSrc, imageSize, imageOption),
				title: val1["id"]+"",
				map: map,
				zIndex:2
			});
			daum.maps.event.addListener(markers_circle[key1], 'mouseover', function() {
				set_map_click(false);
				var d = this;
				if(val1["type"]=="installation"){
					$(".marker-"+d.getTitle()).find("span").css('background-color','#fff2de');
				}
				if(val1["type"]=="sell"){
					$(".marker-"+d.getTitle()).find("span").css('background-color','#fddfe1');
				}
				if(val1["type"]=="full_rent"){
					$(".marker-"+d.getTitle()).find("span").css('background-color','#e2ebfe');
				}
				if(val1["type"]=="monthly_rent"){
					$(".marker-"+d.getTitle()).find("span").css('background-color','#e6fdee');
				}
				if(val1["is_finished"]=="1"){
					$(".marker-"+d.getTitle()).find("span").css('background-color','#ddd');
				}
			});
			daum.maps.event.addListener(markers_circle[key1], 'mouseout', function() {
				set_map_click(true);
				$(".marker").find("span").css('background-color','#fff');
			});
			daum.maps.event.addListener(markers_circle[key1], 'click', function() {
				get_property(val1["id"],val1["address_id"],val1["category_opened"],val1["category_level"]);
			});
		} else {
			var is_yAnchor = 0;
			var is_xAnchor = 0;
			if(c_class=="s"){
				is_yAnchor = -0.4;
				is_xAnchor = 0.3;
			} else if(c_class=="m"){
				is_yAnchor = -0.7;
				is_xAnchor = 0.5;
			} else if(c_class=="l"){
				is_yAnchor = -1;
				is_xAnchor = 0.5;
			}
			markers[key1] = new daum.maps.CustomOverlay({
				clickable : false,
				map: map,
				position: loc,
				content: "",
				yAnchor: is_yAnchor,
				xAnchor: is_xAnchor,
				zIndex: 1
			});
			if(c_class=="s"){
				var imageSrc = "/assets/common/img/obSt_red.png",
				imageSize = new daum.maps.Size(45, 45),
				imageOption = {offset: new daum.maps.Point(20, 0)};
			} else if(c_class=="m"){
				var imageSrc = "/assets/common/img/obMt_red.png",
				imageSize = new daum.maps.Size(60, 60),
				imageOption = {offset: new daum.maps.Point(30, 0)};
			} else if(c_class=="l"){
				var imageSrc = "/assets/common/img/obLt_red.png",
				imageSize = new daum.maps.Size(75, 75),
				imageOption = {offset: new daum.maps.Point(37, 0)};						    
			}
			markers_circle[key1] = new daum.maps.Marker({
				position: loc,
				image: new daum.maps.MarkerImage(imageSrc, imageSize, imageOption),
				title: val1["id"]+"",
				map: map,
				yAnchor: 1,
				zIndex:0
			});
			daum.maps.event.addListener(markers_circle[key1], 'click', function() {
				click_cluster = val1["id"];
				cluster_list(val1["count"],this.getPosition().getLat(), this.getPosition().getLng(), val1["ids"]);
			});
			daum.maps.event.addListener(markers_circle[key1], 'mouseover', function() {
				set_map_click(false);
			});
			daum.maps.event.addListener(markers_circle[key1], 'mouseout', function() {
				set_map_click(true);
			});
			$(".cluster_wrapper").eq(cluster_count).parent().css("pointer-events","none");
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children().css('border-radius','50%');
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children('img:first-child').css('border','2px solid #fff');
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children('img:first-child').addClass('cs');
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children('img:first-child').addClass(val1["id"]);
		
			if(val1["icon_only"]!="2") cluster_count++; //가격,아이콘일 경우엔 카운트에서 제외 해야함. 
		}
		if(val1["icon_only"]=="2") cluster_count++; //클러스터가 1숫자 이미지일 경우엔 카운트를 전부 세줘야함.
	});
	
	var cluster_color = "";
			cluster_color = "rgba(211,75,57,0.9)";
	
	//이미지 클러스터에 오버효과
	$('.cs').parent().hover(function(){
		$(this).children('img:nth-child(2)').css('box-shadow','0 0 15px 15px '+cluster_color);
		$(this).children().css('-webkit-transition','0.3s ease-in-out');
		$(this).children().css('-moz-transition','0.3s ease-in-out');
		$(this).children().css('-o-transition','0.3s ease-in-out');
		$(this).children().css('transition','0.3s ease-in-out');
	},function(){
		if(!$(this).hasClass('hover_active')){
			$(this).children().css('box-shadow','none');
		}
	});
	//이미지 클러스터에 클릭효과
	$('.cs').parent().click(function(){
		$('.cs').parent().removeClass('hover_active');
		$(this).addClass('hover_active');
		$('.cs').css('border','2px solid #fff');
		$('.cs').parent().children().css('box-shadow','none');
		$(this).children('img:nth-child(2)').css('box-shadow','0 0 15px 15px '+cluster_color);
		$('.subwaycon').css('border','4px solid rgba(250,255,255,0.2)');
		$('.subwaycon').css('box-shadow','none');
	});
	//클릭되어 있는 클러스터는 지도를 이동해도 클릭되어 있는 효과를 준다
	if(click_cluster){
		$("."+click_cluster).parent().addClass('hover_active');
		$("."+click_cluster).parent().children().css('border-radius','50%');
		$("."+click_cluster).parent().children('img:nth-child(2)').css('box-shadow','0 0 15px 15px '+cluster_color);
	}
}
/*****************************************************
* 지도상에서 하나의 매물을 클릭했을 경우 모달창을 띄움
*****************************************************/
function get_property(id,address_id,category_opened,category_level){
			var member_id = "";
		var member_type = "";
		var permit_area = "";
		var level = "";
		/*회원인증 체크(로그인,비로그인)*/
		if(category_opened=="N" && member_id==""){
			$("#signup").find(".leanModal").click();
		}
		/*회원인증 체크(간편회원은 볼 수 없다)*/
		else if(category_opened=="N" && member_type=="general" && level=="1"){
			$("#simple-member").find(".leanModal").click();
		}
		else{
			/*허용지역 체크*/
			if(permit_area!=""){
				permit_area = permit_area.split(",");
				
				if($.inArray(address_id,permit_area) > -1){
					product_modal(id);
				}
				else{
					$("#permit-area").find(".leanModal").click();
				}
			}
			/*회원단계 체크(프리미엄회원 사용시, *프리미엄회원은 일반회원만 적용되는 사항)*/
			else{
									product_modal(id);
							}
		}
	}
/*****************************************************
* 매물 좌표를 표시
******************************************************/
function get_property_base(lat,lng,remove){
	if(remove!=1){
		var imageSrc = '/assets/common/img/map_marker.gif',
		imageSize = new daum.maps.Size(40, 40),
		imageOption = {offset: new daum.maps.Point(0, 0)};
	} else {
		var imageSrc = '',
		imageSize = new daum.maps.Size(40, 40),
		imageOption = {offset: new daum.maps.Point(0, 0)};
	}
	
		
	var markerImage = new daum.maps.MarkerImage(imageSrc, imageSize, imageOption),
		markerPosition = new daum.maps.LatLng(lat, lng);
	reset_coord_marker();
	marker = new daum.maps.Marker({
		position: markerPosition, 
		image: markerImage,
		zIndex: 6
	});
	marker.setMap(map);
}
/*****************************************************
* 단지 매물 목록을 가져온다.
******************************************************/
danzi_address_id_val='';//검색추가
danzi_name_val='';//검색추가
function danzi_list(danzi_address_id, danzi_name){
	danzi_address_id_val=danzi_address_id;//검색추가
	danzi_name_val=danzi_name;//검색추가
	is_cluster='danzi';//검색추가
	reset_coord_marker();
	reset_right_value();
	$("#danzi_address_id").val(danzi_address_id);
	$("#right_danzi_name").val(danzi_name);
	$("#where").html(danzi_name+" 검색결과 (1)");
	$("#where_wrapper").removeClass("display-none");
	$(".sorting_section").hide();//검색추가
	danzi_cluster_hover();	
	right_exists = false;
	if($("#biz_map").length > 0 && $("#biz_map").val()=="1"){
		get_map_list_biz(0);
	}
	else{
		get_map_list(0);
	}
}
/*****************************************************
* 매물 클러스터 목록을 가져온다.
*****************************************************/
cluster_count='';//검색추가
cluster_x='';//검색추가
cluster_y='';//검색추가
cluster_ids='';//검색추가
function cluster_list(count, x, y, ids){
	reset_coord_marker();
	reset_right_value();
	$("#cluster_x").val(x);
	$("#cluster_y").val(y);
	$("#cluster_ids").val(ids);
	is_cluster='cluster';//검색추가
	cluster_count=count;//검색추가
	cluster_x=x;//검색추가
	cluster_y=y;//검색추가
	cluster_ids=ids;//검색추가
	$("#where").html("검색결과 ("+count+")");
	$("#where_wrapper").removeClass("display-none");
	$(".sorting_section").hide();//검색추가
	right_exists = false;
	if($("#biz_map").length > 0 && $("#biz_map").val()=="1"){
		get_map_list_biz(0);
	}
	else{
		get_map_list(0);
	}
}
/*****************************************************
* 우측 매물 목록을 보여준다.
*
* - address_id를 넘겼을 경우 동에 대한 매물을 보여준다.
* - x,y 클러스터 좌표를 넘겼을 경우 x,y 범위에 대한 매물을 보여준다.
*****************************************************/
function get_map_list(page){
	
	if(right_exists) return false;
	loading_delay(true);
	
	$.ajax({
		type	: "POST",
		url		: "/main/get_all_server_list/"+page+"/"+map.getBounds().getSouthWest().getLat()+"/"+map.getBounds().getNorthEast().getLat()+"/"+map.getBounds().getSouthWest().getLng()+"/"+map.getBounds().getNorthEast().getLng()+"/"+init_zoom+"/"+Math.round(new Date().getTime()),
		cache: false,
		async: false,
		data: $("#search_form").serialize(),
		dataType: 'json',
		success: function(data) {
			$.each(data, function(key, val) {
				if(key=="result") {
					str = val;
				}
				if(key=="total"){
					total = val;
					$(".result_label").html(" 검색결과 " + val);
					
				}
				if(key=="premium_total"){
					$("#premium_total").text(val);
				}
				if(key=="premium_mean"){
					$("#premium_mean").text(val);
				}
				if(key=="paging"){
					if(total<=val){
						$("#pagination_more").hide();
					} else {
						$("#pagination_more").show();
					}
					
					next_page = val;
					$("#next_page").val(val);
				}
			});
			if($.trim(str)==""){
				$("#pagination_more").hide();
				str = " 검색 결과가 없습니다
";
			} else {
				$('#no_search_data').hide();
			}
			if(next_page<=21){
				$("#map_search_list").html(str);			
				$("#map_list").animate({
					scrollTop: 0
				}, 600);
			} else {
				$("#map_search_list").append(str);
			}
			$("#loading").hide();
			$(".relist").mouseenter(function(){
																});
			map.setDraggable(true);    
			map.setZoomable(true);
			link_init($('.view_product'));
			
			setTimeout(function() {
				  idle_disable = 0;
			}, 1000);
			
			setTimeout(function(){
				loading_delay(false);
			}, 300);
			login_leanModal();
			if($("#danzi_address_id").val()!=0){
				$("#danzi_sell").html(""+data["sell_count"]+"건");
				$("#danzi_fullrent").html(""+data["full_rent_count"]+"건");
				$("#danzi_rent").html(""+data["monthly_rent_count"]+"건");
				$("#danzi_count_section").removeClass("display-none");
			}
			else{
				$("#danzi_count_section").addClass("display-none");
			}
			secret_tooltip();
		}
	});
	right_exists = true;
}
/*****************************************************
* 더보기 버튼 이벤트
*****************************************************/
function more(){
	right_exists = false;
	if($("#biz_map").length > 0 && $("#biz_map").val()=="1"){
		get_map_list_biz($("#next_page").val());
	}
	else{
		get_map_list($("#next_page").val());
	}
}
/*****************************************************
* 지도에 표시되는 좌표마커 초기화
*****************************************************/
function reset_coord_marker(){
	if(marker){
		marker.setMap(null);
	}
}
/*****************************************************
* 지도 좌표 이동 시키기
*****************************************************/
function move_map(lat,lng, pzoom){
	idle_disable = 1;
	map.setCenter(new  daum.maps.LatLng(lat, lng));
	map.setLevel(pzoom);
	idle_disable = 0;
}
/*****************************************************
* 지도 좌표 확대하면서 이동 시키기
*****************************************************/
function map_zoom(lat,lng,zoom){
	move_map(lat,lng,zoom);
	call_map();
}
/*****************************************************
* 지도에 중개업소 정보들을 나타낸다.
*****************************************************/
function get_marker_map_biz(val){
	var cluster_count = 0;
	$.each(val, function(key1, val1) {
		// 마커의 위치 지정
		var loc = new daum.maps.LatLng(val1["lat"], val1["lng"]);
		
		// 원의 클래스 정의
		var c_class = "s";
		if(val1["count"]>=10) c_class = "m";
		else if(val1["count"]>=100) c_class = "l";
		// count가 1일 경우에는 숫자 이미지를 표시해 주고 1 이상일 경우에는 클러스터를 보여준다.
		if(val1["count"]=="1"){
			var imageSrc = "/assets/common/img/obSt_violet.png",
				imageSize = new daum.maps.Size(45, 45),
				imageOption = {offset: new daum.maps.Point(20, 0)};
			var icon_count = val1["count"];
			markers[key1] = new daum.maps.CustomOverlay({
				map: map,
				position: loc,
				content: "",
				yAnchor: -0.4,
				xAnchor: 0.3,
				zIndex: 3
			});
			markers_circle[key1] = new daum.maps.Marker({
				position: loc,
				image: new daum.maps.MarkerImage(imageSrc, imageSize, imageOption),
				map: map,
				zIndex:2
			});
			daum.maps.event.addListener(markers_circle[key1], 'click', function() {
				//location.href='/biz/view/'+val1["id"];
			});
		} else {
			var is_yAnchor = 0;
			var is_xAnchor = 0;
			if(c_class=="s"){
				is_yAnchor = -0.4;
				is_xAnchor = 0.3;
			} else if(c_class=="m"){
				is_yAnchor = -0.7;
				is_xAnchor = 0.5;
			} else if(c_class=="l"){
				is_yAnchor = -1;
				is_xAnchor = 0.5;
			}
			markers[key1] = new daum.maps.CustomOverlay({
				clickable : false,
				map: map,
				position: loc,
				content: "",
				yAnchor: is_yAnchor,
				xAnchor: is_xAnchor,
				zIndex: 1
			});
			if(c_class=="s"){
				var imageSrc = "/assets/common/img/obSt_violet.png",
				imageSize = new daum.maps.Size(45, 45),
				imageOption = {offset: new daum.maps.Point(20, 0)};
			} else if(c_class=="m"){
				var imageSrc = "/assets/common/img/obMt_violet.png",
				imageSize = new daum.maps.Size(60, 60),
				imageOption = {offset: new daum.maps.Point(30, 0)};
			} else if(c_class=="l"){
				var imageSrc = "/assets/common/img/obLt_violet.png",
				imageSize = new daum.maps.Size(75, 75),
				imageOption = {offset: new daum.maps.Point(37, 0)};						    
			}
			markers_circle[key1] = new daum.maps.Marker({
				position: loc,
				image: new daum.maps.MarkerImage(imageSrc, imageSize, imageOption),
				title: val1["id"]+"",
				map: map,
				yAnchor: 1,
				zIndex:0
			});
			daum.maps.event.addListener(markers_circle[key1], 'click', function() {
				click_cluster = val1["id"];
				cluster_list_biz(val1["count"],this.getPosition().getLat(), this.getPosition().getLng(), val1["ids"]);
			});
			$(".cluster_wrapper").eq(cluster_count).parent().css("pointer-events","none");
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children().css('border-radius','50%');
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children('img:first-child').css('border','2px solid #fff');
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children('img:first-child').addClass('cs');
			$(".cluster_wrapper").eq(cluster_count).parent().next('div').children('img:first-child').addClass(val1["id"]);
		}
		cluster_count++; //클러스터가 1숫자 이미지일 경우엔 카운트를 전부 세줘야함.
	});
	
	var cluster_color = "rgba(117,103,174,0.9)";
	//이미지 클러스터에 오버효과
	$('.cs').parent().hover(function(){
		$(this).children('img:nth-child(2)').css('box-shadow','0 0 15px 15px '+cluster_color);
		$(this).children().css('-webkit-transition','0.3s ease-in-out');
		$(this).children().css('-moz-transition','0.3s ease-in-out');
		$(this).children().css('-o-transition','0.3s ease-in-out');
		$(this).children().css('transition','0.3s ease-in-out');
	},function(){
		if(!$(this).hasClass('hover_active')){
			$(this).children().css('box-shadow','none');
		}
	});
	//이미지 클러스터에 클릭효과
	$('.cs').parent().click(function(){
		$('.cs').parent().removeClass('hover_active');
		$(this).addClass('hover_active');
		$('.cs').css('border','2px solid #fff');
		$('.cs').parent().children().css('box-shadow','none');
		$(this).children('img:nth-child(2)').css('box-shadow','0 0 15px 15px '+cluster_color);
		$('.subwaycon').css('border','4px solid rgba(250,255,255,0.2)');
		$('.subwaycon').css('box-shadow','none');
	});
	//클릭되어 있는 클러스터는 지도를 이동해도 클릭되어 있는 효과를 준다
	if(click_cluster){
		$("."+click_cluster).parent().addClass('hover_active');
		$("."+click_cluster).parent().children().css('border-radius','50%');
		$("."+click_cluster).parent().children('img:nth-child(2)').css('box-shadow','0 0 15px 15px '+cluster_color);
	}
}
/*****************************************************
* 중개업소 클러스터 목록을 가져온다.
*****************************************************/
function cluster_list_biz(count, x, y, ids){
	
	reset_coord_marker();
	reset_right_value();
	$("#cluster_x").val(x);
	$("#cluster_y").val(y);
	$("#cluster_ids").val(ids);
	is_cluster='';//검색추가
	$("#where").html("검색결과 ("+count+")");
	$("#where_wrapper").removeClass("display-none");
	$(".sorting_section").hide();//검색추가
	right_exists = false;
	get_map_list_biz(0);
}
/*****************************************************
* 우측 중개업소 목록을 보여준다.
*****************************************************/
function get_map_list_biz(page){
	if(right_exists) return false;
	loading_delay(true);
	$.ajax({
		type	: "POST",
		url		: "/main/get_all_server_list_biz/"+page+"/"+map.getBounds().getSouthWest().getLat()+"/"+map.getBounds().getNorthEast().getLat()+"/"+map.getBounds().getSouthWest().getLng()+"/"+map.getBounds().getNorthEast().getLng()+"/"+init_zoom+"/"+Math.round(new Date().getTime()),
		cache: false,
		async: false,
		data: $("#search_form").serialize(),
		dataType: 'json',
		success: function(data) {
			$.each(data, function(key, val) {
				if(key=="result") {
					str = val;
				}
				if(key=="total"){
					total = val;
					$(".result_label").html(" 검색결과 " + val);
				}
				if(key=="paging"){
					if(total<=val){
						$("#pagination_more").hide();
					} else {
						$("#pagination_more").show();
					}
					
					next_page = val;
					$("#next_page").val(val);
				}
			});
			if($.trim(str)==""){
				$("#pagination_more").hide();
				str = " 검색 결과가 없습니다
";
			} else {
				$('#no_search_data').hide();
			}
			if(next_page<=21){
				$("#map_search_list").html(str);			
				$("#map_list").animate({
					scrollTop: 0
				}, 600);
			} else {
				$("#map_search_list").append(str);
			}
			$("#loading").hide();
			
			$(".relist").mouseenter(function(){
																});
			map.setDraggable(true);    
			map.setZoomable(true);
			
			setTimeout(function() {
				  idle_disable = 0;
			}, 1000);
			
			setTimeout(function(){
				loading_delay(false);
			}, 300);
			login_leanModal();
		}
	});
	right_exists = true;
}
/*****************************************************
* 매물, 중개업소 버튼 스위칭
*****************************************************/
function biz_switch(val){
	$(".biz_switch_button").find("a").removeClass("active");
	if(val=="1"){
		$("#biz_btn1").addClass("active");
	}
	else{
		$("#biz_btn").addClass("active");
	}
	if(val){
		$(".sorting_section").slideUp();
		$(".maplist_1, .maplist_3, .maplist_4, .maplist_5").css("padding-right","432px");
		$(".map_list_1, .map_list_3, .map_list_4, .map_list_5").animate({"width" : "430px"},"fast");
	}
	else{
		if($(".maplist_1").length > 0){
			$(".maplist_1").css("padding-right","402px");
			$(".map_list_1").animate({"width" : "400px"},"fast");
		}
		if($(".maplist_3").length > 0){
			$(".maplist_3").css("padding-right","902px");
			$(".map_list_3").animate({"width" : "900px"},"fast");
		}
		if($(".maplist_4").length > 0){
			$(".maplist_4").css("padding-right","420px");
			$(".map_list_4").animate({"width" : "413px"},"fast");
		}
		if($(".maplist_5").length > 0){
			$(".maplist_5").css("padding-right","854px");
			$(".map_list_5").animate({"width" : "850px"},"fast");
		}
		$(".sorting_section").slideDown();
	}
	$("#biz_map").val(val);
	call_map();
	map.relayout();
}