var mapCurrentAreacode = "";
var curIdx = 0; 
var mapId = [];
var mapIdBase = [];

/***
* 테스트 버젼 :  좌측 리스트에서  마우스 오버시
***/
function mOver(event, dmap, code, markObj, options, ttContents ){
	try{
		var event = event?event:window.event;

		if(!markObj) return;
		
		// 리스트보기일 경우에는 단지 마우스 오버시 툴팁 보이지 않음
		if( options.ctrl ){
			if(options.ctrl.status.isExtendList  == true){
				return;
			}
		}

		if(dmap){
			switch(dmap.mapName){
			case "baseMap":
				document.getElementById("mapIframeBase").contentWindow.showTooltip(event.type, dmap, code, markObj, options );
				break;
			case "localMap":
			case "subwayMap":
				document.getElementById("mapif").contentWindow.showTooltip(event.type, dmap, code, markObj, options);
				break;
			default:
				document.getElementById("mapif").contentWindow.showTooltip(event.type, dmap, code, markObj, options);
				break;
			}
	    }else{
	    	document.getElementById("mapif").contentWindow.showTooltip(event.type, dmap, code, markObj, options);
	    }
		if( event.type == "click"){
			curIdx = this.options.idx;
			if( opt && opt.mini != 'false' ){
				callSymbolClickIframe();
			}
		}
	}catch(e){
		alert(e.message);
	}
}

/***
* 좌측 리스트에서  마우스 오버시
***/
function listOver(event, id, x, y, imgListObj, dmap, opt){
	try{
		var event = event?event:window.event;
		if(!imgListObj) return;
		if(dmap){
			switch(dmap.mapName){
			case "baseMap":
				document.getElementById("mapIframeBase").contentWindow.onListOverShowIW(event.type, id, x, y, imgListObj, dmap, opt );
				break;
			case "danji_place_map":
			case "localMap":
			case "subwayMap":
				document.getElementById("mapif").contentWindow.onListOverShowIW(event.type, id, x, y, imgListObj, dmap,  opt );
				break;
			default:
				document.getElementById("mapif").contentWindow.onListOverShowIW(event.type, id, x, y, imgListObj);
				break;
			}
	    }else{
	    	document.getElementById("mapif").contentWindow.onListOverShowIW(event.type, id, x, y, imgListObj);
	    }
		if( event.type == "click"){
			curIdx = id;
			if( opt && opt.mini != 'false' ){
				callSymbolClickIframe();
			}
		}
	}catch(e){
	}
}

// 단지 리스트 마우스 아웃시
function listOut(id, map){
	try{
		if( curIdx == id ){
			return;
		}
		
		if(map.mapName == "baseMap"){
			var ifr = document.getElementById("mapIframeBase").contentWindow; 
			if(ifr.baseLayerWindow){
				ifr.baseLayerWindow.hide();
			}	
		}else{
			var ifr = document.getElementById("mapif").contentWindow;
			if( ifr.layerWindow ){
				ifr.layerWindow.hide();
			}else if(ifr.infowindow){
				ifr.infowindow.hide();
			}
		} 
	}catch(e){}
}


function onListOut(id, map, type){
 
	//if( type == 'tag'){
		if(map.mapName == "baseMap"){
			var ifr = document.getElementById("mapIframeBase").contentWindow; 
			if(ifr.baseLayerWindow){
				ifr.baseLayerWindow.hide();
			}	
		}else{
			var ifr = document.getElementById("mapif").contentWindow;
			if( ifr.layerWindow ){
				ifr.layerWindow.hide();
			}else if(ifr.infowindow){
				ifr.infowindow.hide();
			}
		} 
	//}
}

function moreLocalInfo(url){
	var code = "E01"; 
	var concate = "?"; 
	if(document.getElementById("localCode")){
		code = document.getElementById("localCode").value; 
	}
	if(url.indexOf('?') != -1){
		concate = "&"; 
	}
	document.location = url + concate + "placeCateCode=" + code; 
}
// 맵 이동시
function MapMovedForEstate( mapObj, xpos, ypos, scale ){
    var url = "/mapMove.daum?xpos="+xpos+"&ypos="+ypos+"&areacode="+mapCurrentAreacode;
    dynamicScript.call( url );
}

//지역이 바뀔때 가이드 제시를 위한 호출함수
function MapMovedComplete( data ){
	try{
    if( data.areacode != "" && mapCurrentAreacode != data.areacode ){
        var obj = UI.$("curInfoLayer");
 
        if( obj ){
            obj.style.display = "block";
            obj.style.display = "inline";
        }
		var form = document.pathForm;
		var cateCode = form.cateCode.value;
		var allCateCodes = form.allCateCodesValue.value;
		var saleType = form.saleType.value;
		var priceCode = form.priceCode.value;
		var sizeCode = form.sizeCode.value;
		var themeId = form.themeId.value;
 
	    var objText = UI.$("CurrentText");
	    objText.innerHTML = "";
	    objText.innerHTML = '<strong>'+mapCurrentAreaname+'</strong>-> <strong>'+data.areaname+'</strong>으로  <a href="/maemul/area/'+data.areacode+'/'+cateCode+'/'+allCateCodes+'/'+saleType+'/'+'summary?themeId=' + themeId + '" onclick=\'return gLink(null, "ZCES", "2", "2");\'><img src="http://fn.daum-img.net/image/estate/2008/maemulSise/new_detail/btn_move.gif" width="48" height="18" /></a>';

	    UI.$("opacityBg").style.width = objText.clientWidth + 8+'px';
    }
	}catch(e){
		//console.debug(e.message);
	}
}

// base 지역정보에서 카테고리 클릭시 데이터 받아오기
var PlaceGetData = function( type ){
	try{
    this.type = type;// 지역별, 역세권별, 단지 구분
    this.mHandle = null;
    this.data = {
        areacode : null,
        stationcode : null,
        danjiid : null,
		saleType : "",
		cateCode : "",
		allCateCodes : "", 
		allCateCodesValue : ""
    };
    this.prevClickObj = UI.$("cateE01");
	}catch(e){
		//alert(e.message);
	}
}
PlaceGetData.prototype = {
    init : function(){
	//this.resetMap();
    },
    setAreaCode : function( val ){ this.data.areacode = val; },
    setStationId : function( val ){ this.data.stationid = val; },
    setDanjiId : function( val ){ this.data.danjiid = val; },
	setSaleTypeCode : function( val ){ this.data.saleType = val; },
	setCateCode : function( val ){ this.data.cateCode = val; },
	setAllCateCode : function( val ){ this.data.allCateCodes = val; },
	setAllCateCodeValue : function( val ){ this.data.allCateCodesValue = val; },
    getUrl : function( cateCode ){
        var url = null;
        switch( this.type ){
        case "area":
            if( this.data.areacode != null ){
                url = "/maemul/AreaPlace4Box.daum";
                param = "areacode="+this.data.areacode+"&placeCateCode="+cateCode;
            }
            break;
        case "subway":
            if( this.data.stationid != null ){
                url = "/maemul/SubwayPlace4Box.daum";
                param = "stationcode="+this.data.stationid+"&placeCateCode="+cateCode;
            }
            break;
        case "detail":
        case "danji":
            if( this.data.danjiid != null ){
                url = "/maemul/DanjiPlace4Box.daum";
                param = "danjiId="+this.data.danjiid+"&placeCateCode="+cateCode;
            }
            break;
        }
		param += this.getNilTag( cateCode );
        return {url:url,param:param};
    },
    send : function( cateCode, clickObj ){
        if( clickObj ){
            if( this.prevClickObj )this.prevClickObj.className = this.prevClickObj.className.replace(" on","");
            
            clickObj.className += " on";
            this.prevClickObj = clickObj;
        }
		if( document.getElementById("localCode")){
			document.getElementById("localCode").value = cateCode; 
		}
        
        var urlData = this.getUrl( cateCode );
        var url = urlData.url;
        if( url == null ){
            alert("URL을 만들 수 없습니다");
            return false;            
        }
                
        var ajax = new FN.Ajax( {url:url} );
        ajax.options.onComplete = this.response.bind(this);
        ajax.options.param = urlData.param;
        ajax.send();
        
    },
	getNilTag : function( cateCode ){
		var nilTag = "";
		if( cateCode == "A01" )nilTag = "nursery"; //어린이집
		else if( cateCode == "A02" )nilTag = "kindergarten"; //유치원  
		else if( cateCode == "A03" )nilTag = "elementary"; //초등학교    
		else if( cateCode == "A04" )nilTag = "middle"; //중학교 
		else if( cateCode == "A05" )nilTag = "high"; //고등학교    
		else if( cateCode == "A06" )nilTag = "university"; //대학(원)   
		else if( cateCode == "A07" )nilTag = "institute"; //학원  
		else if( cateCode == "B01" )nilTag = "park"; //공원  
		else if( cateCode == "B02" )nilTag = "seniorcenter"; //노인정 
		else if( cateCode == "B03" )nilTag = "mart"; //마트/편의점  
		else if( cateCode == "B04" )nilTag = "bathroom"; //목욕탕 
		else if( cateCode == "B05" )nilTag = "department"; //백화점 
		else if( cateCode == "B06" )nilTag = "laundry"; //세탁소 
		else if( cateCode == "B07" )nilTag = "sport"; //스포츠 
		else if( cateCode == "B08" )nilTag = "food"; //음식점 
		else if( cateCode == "B10" )nilTag = "residents"; //주민센터    
		else if( cateCode == "B11" )nilTag = "bank"; //은행  
		else if( cateCode == "B12" )nilTag = "library"; //도서관 
		else if( cateCode == "B13" )nilTag = "post"; //우체국 
		else if( cateCode == "B14" )nilTag = "hospital"; //병원  
		else if( cateCode == "C01" )nilTag = "subway"; //지하철 
		else if( cateCode == "C02" )nilTag = "bus"; //버스  
		else if( cateCode == "E01" )nilTag = "agency"; //중개업소
		return "&nil_profile=estatetop&nil_local="+nilTag;
		
	},
    response : function( res ){
		try{
        var result = eval("("+res.responseText+")" );
        var objCate = UI.$("placeBaseCate");
        var objCount= UI.$("placeBaseCount");
        var objList = UI.$("placeBaseList");
        
        objCate.innerHTML = result.info.selectedCate.name; 
        objCount.innerHTML = "총 "+result.info.selectedCate.count+"건";
        var allCateCodes =""; 
        var ul = "";
        
        for( var num=0; num< result.data.length; num++){
            var item = result.data[num];
            var linkUrl = "";
			var target = "_blank";
            
            if(  item.placeType == "SUBWAY" ){ 
				allCateCodes = this.data.allCateCodes.replace(/,/gi,'');
                linkUrl = "/maemul/subway/*/*/"+item.code+"/"+this.data.cateCode+"/"+allCateCodes+"/"+this.data.saleType+"/*/summary";         
				target = "_top";
            }else{
            	linkUrl = item.localUrl;
            }
            ul += '<li class="itm'+((num==0)?' first':'')+'">';
            ul += '<img src="http://fn.daum-img.net/image/estate/2008/maemulSise/icon_s'+item.seq+'.gif" class="num" title="'+item.seq+'">';
			var iname = escape( item.name );

            if( item.distance != "" && item.distance != "0" ){
				if( item.placeType == "SUBWAY"  ) {
					ul += '<a href="#" onclick="goSpot(\''+item.seq+'\', parseInt('+ item.pos.x + ',10), parseInt('+item.pos.y+',10), dmapLocal);return false;" class="lnk gray_blue" onmouseover="listOver(event, \''+item.seq+'\',\''+item.pos.x+'\',\''+item.pos.y+'\',mapIdBase,dmapLocal,{menu_type:\''+item.menu_type + '\', name1:\''+item.name1 + '\', name2:\''+item.name2 + '\', lineCode:\''+item.lineCode + '\', stationCode:\''+item.stationCode + '\', cateCode:\'' + this.data.cateCode+"/"+allCateCodes+"/"+this.data.saleType + '\', placeType:\'' + item.placeType + '\'});" target="'+target+'">'+UI.length( item.name, 16, ".." )+'</a>';
				}else if(item.placeType == "AGENCY"){
					var len = 26; 
					var agencyYn = false;
					if(item.agencyid !="" && UI.$("txtAgencyId") && UI.$("txtAgencyId").value == item.agencyid ){
						len = 16;
						agencyYn = true;
					}					
					ul += '<a href="#" onclick="goSpot(\''+item.seq+'\', parseInt('+ item.pos.x + ',10), parseInt('+item.pos.y+',10), dmapLocal);return false;" title="'+item.name+'" class="lnk gray_blue" onmouseover="listOver(event, \''+item.seq+'\',\''+item.pos.x+'\',\''+item.pos.y+'\',mapIdBase,dmapLocal,{menu_type:\''+item.menu_type + '\', name:\''+item.name + '\',addr:\''+item.addr +'\',placeType:\'' + item.placeType + '\', localUrl:\'' + item.localUrl + '\', tel:\'' + item.tel + '\'});" target="'+target+'">'+UI.length( item.name, len, ".." )+'</a>';
					if(agencyYn == true ){
						ul += '<em class="icnAgency" title="지정업소">지정업소</em>';
					}
				}else{
					ul += '<a href="#" onclick="goSpot(\''+item.seq+'\', parseInt('+ item.pos.x + ',10), parseInt('+item.pos.y+',10), dmapLocal);return false;" title="'+item.name+'" class="lnk gray_blue" onmouseover="listOver(event, \''+item.seq+'\',\''+item.pos.x+'\',\''+item.pos.y+'\',mapIdBase,dmapLocal,{menu_type:\''+item.menu_type + '\', name:\''+item.name + '\',addr:\''+item.addr +'\',placeType:\'' + item.placeType + '\', localUrl:\'' + item.localUrl + '\', tel:\'' + item.tel + '\'});" target="'+target+'">'+UI.length( item.name, 16, ".." )+'</a>';
				}
				if( item.placeType != "AGENCY" ){
					ul += '<span class="range blue">'+item.distance+'m</span>';
				}	
            } else {
				if(item.placeType == "SUBWAY" ){
	                ul += '<a href="#" onclick="goSpot(\''+item.seq+'\', parseInt('+ item.pos.x + ',10), parseInt('+item.pos.y+',10), dmapLocal);return false;" title="'+item.name+'" class="lnk gray_blue" onmouseover="listOver(event, \''+item.seq+'\',\''+item.pos.x+'\',\''+item.pos.y+'\',mapIdBase,dmapLocal,{menu_type:\''+item.menu_type + '\', name1:\''+item.name1 + '\', name2:\''+item.name2 + '\', lineCode:\''+item.lineCode + '\', stationCode:\''+item.stationCode +'\', cateCode:\'' + this.data.cateCode+"/"+allCateCodes+"/"+this.data.saleType + '\', placeType:\'' + item.placeType + '\'});" target="'+target+'">'+UI.length( item.name, 26, ".." )+'</a>';
				}else if(item.placeType == "AGENCY"){
					var len = 26; 
					var agencyYn = false;
					if(item.agencyid !="" && UI.$("txtAgencyId") && UI.$("txtAgencyId").value == item.agencyid ){
						len = 16;
						agencyYn = true;
					}
					ul += '<a href="#" onclick="goSpot(\''+item.seq+'\', parseInt('+ item.pos.x + ',10), parseInt('+item.pos.y+',10), dmapLocal);return false;" title="'+item.name+'" class="lnk gray_blue" onmouseover="listOver(event, \''+item.seq+'\',\''+item.pos.x+'\',\''+item.pos.y+'\',mapIdBase,dmapLocal,{menu_type:\''+item.menu_type + '\', name:\''+item.name + '\',addr:\''+item.addr +'\',placeType:\'' + item.placeType + '\', localUrl:\'' + item.localUrl + '\', tel:\'' + item.tel + '\'});" target="'+target+'">'+UI.length( item.name, len, ".." )+'</a>';
					if(agencyYn == true ){
						ul += '<em class="icnAgency" title="지정업소">지정업소</em>';
					}					
				}else{
	                ul += '<a href="#" onclick="goSpot(\''+item.seq+'\', parseInt('+ item.pos.x + ',10), parseInt('+item.pos.y+',10), dmapLocal);return false;" title="'+item.name+'" class="lnk gray_blue" onmouseover="listOver(event, \''+item.seq+'\',\''+item.pos.x+'\',\''+item.pos.y+'\',mapIdBase,dmapLocal,{menu_type:\''+item.menu_type + '\', name:\''+item.name + '\',addr:\''+item.addr +'\',placeType:\'' + item.placeType + '\', localUrl:\'' + item.localUrl + '\', tel:\'' + item.tel + '\'});" target="'+target+'">'+UI.length( item.name, 26, ".." )+'</a>';
				}
            }
            ul += '</li>';
			// infoWinUrl을 새로 만들어줌 
			result.data[num].infoWinUrl = this.makeLinkUrl( result.data[num] );
			result.data[num].size = this.markSize(result.data[num].placeType);
			 
			if(document.getElementById("mapIframeBase").contentWindow.baseLayerWindow){
				document.getElementById("mapIframeBase").contentWindow.baseLayerWindow = null;
			}
        }
        
        if( result.data.length > 0 ){
            placeListBase = result.data;
        } else {
			ul = '<li><p class="noItemPlace"><strong>\''+result.info.selectedCate.name+'\'</strong> 정보가 없습니다.</p></li>'; 
            placeListBase = [];            
        }
        this.resetMap();
        objList.innerHTML = ul;      
        if( document.getElementById("danjiPlaceDummy")){
        	document.getElementById("danjiPlaceDummy").src = "http://realestate.daum.net/clickDummy/place";
        }
        
		var frm = document.pathForm;
		if( frm.naviType.value != "subway"){
			ifr = document.getElementById("mapIframeBase").contentWindow; 
			ifr.radiusDraw(dmapLocal, "", "" , 'base');
		}
		
		}catch(e){
			//alert(e.message);
		}
    },
	makeLinkUrl : function( result ){
		var url = "";
		var allCateCodes = this.data.allCateCodes.replace(/,/gi,'');
		if( result.placeType == "SUBWAY"){
			url = "/maemul/placeToolTip.daum?placeId="+result.code+"&placeType="+result.placeType+"&saleTypeCode="+this.data.saleType+"&num="+result.seq+"&viewMode=mini&cateCode=" + this.data.cateCode + "&extCateCodes=" +allCateCodes;
		}else{
			url = "/maemul/placeToolTip.daum?placeId="+result.code+"&placeType="+result.placeType+"&saleTypeCode="+this.data.saleType+"&num="+result.seq+"&viewMode=mini";
		}
		return url;
	},
	
	markSize : function(placeType){
		var size= []; 
		if( placeType == 'EDU' || placeType == 'LIFE' || placeType == "AGENCY") {
			size = {width:230, height:55};
		} else if( placeType == 'SUBWAY' || placeType == 'BUS') {
			size = {width:250, height:33};
		}
		return size; 
	}, 
	
    resetMap : function(){
		try{
	        // 이전꺼 지우고
			dmapLocal.clearOverlay();
	        baseInfowindow = null; // 인포윈도우 clear
	        var ifr = document.getElementById("mapIframeBase").contentWindow;
	        ifr.addSymbolEstate(  dmapLocal, danjiListCurrentPlace, danjiOptCurrentPlace );
	        // 새로 그리기  
	        if( placeListBase.length > 0 ){      
	            mapIdBase = ifr.addSymbolEstate( dmapLocal, placeListBase, placeOptBase );
	        }
		}catch(e){} 	
    }
}

//주변단지 보기/끄기
function hideNearDanji(){
	try{
		if(mapHandle){
			mapHandle.removeOverlay( danjiOpt.symbolGroup );
		}
	}
	catch(e){
	}
}

function showNearDanji(){
	try{
	    var url = "";
	    var param = "";
	    var form = document.pathForm;
	    var mode = form.menuType.value;  
		var allCateCodes = form.allCateCodes.value.replace(/,/gi,'');
 
	    switch( mode ){ 
	    case "area":
	        url = "/maemul/BoundaryDanjiListByArea.daum";
	        param = "areacode="+form.areaCode.value;
	        param += "&catecode="+form.cateCode.value;
	        param += "&extCatecodes="+allCateCodes;
	        break;
	    case "danji":
	        url = "/maemul/BoundaryDanjiListByDanji.daum";
	        param = "danjiid="+form.danjiId.value;
	        param += "&catecode="+form.cateCode.value;
	        param += "&extCatecodes="+allCateCodes;
	        break;
	    case "subway":
	        url = "/maemul/BoundaryDanjiListBySubway.daum";
	        param = "subwaycode="+form.stationCode.value;
	        param += "&catecode="+form.cateCode.value;
	        param += "&extCatecodes="+allCateCodes;
	        break;
	    }
		param += "&saletype="+form.saleType.value;
		/*
		if( form.param && form.param.value != "" ){
			param += "&param="+form.param.value;
		} else if( form.stationCode && form.stationCode.value != "" ){
			param += "&param=subway%7C*%7C*%7C"+form.stationCode.value+"%7C"+form.cateCode.value+"%7C"+allCateCodes+"%7C"+form.saleType.value+"%7C"+form.distanceCode.value;
		}
	*/
		param += "&nil_profile=estatetop&nil_local=arounddanji";
	    if( url == "" ) return false;
	    
		var ajax = new FN.Ajax( {url:url} );
		ajax.options.onComplete = reponseNearDanjilist.bind(this);
		if( param ){
		    ajax.options.param = param;
		}
 
		ajax.send();
	}catch(e){
		alert(e.message);
	}
}
function reponseNearDanjilist( res ){
	try{
	    danjiList = eval("("+res.responseText+")" );
	    var form = document.pathForm;
	    var mode = form.menuType.value;
	    mapHandle = document.getElementById("mapif").contentWindow.dmap;
	    document.getElementById("mapif").contentWindow.addSymbolEstate(  mapHandle, danjiList, danjiOpt );
	}catch(e){
		//alert(e.message);
	}
}

/* 통합정보의 현재 동으로 이동 하기 */
function mapMovedCurrentPos(){
    gLink(null, "ZCES", "1", "4");
    document.getElementById("mapif").contentWindow.mapMovedPos(); 
}

function goSpot(id, x, y, map){
	document.getElementById(ifrName).contentWindow.goSpotIfr(id, x, y, map);
	//callSymbolClickIframe();
}

function mapMouseOver(){
	UI.$('bigMap').className = "over";
}
function mapMouseOut(){
	UI.$('bigMap').className = "";	
}

function goRoadview(map, _x, _y, _mnuType){
	try{
		var ifr = document.getElementById(ifrName).contentWindow;
		//if( mapFrameCtl.status.isExtendList == false ){
			mapFrameCtl.mapChnaged(1, _mnuType);
		//}	 
		if( UI.$("mapCon").className == "extendList extendHeight" ){
			mapFrameCtl.setExtendList("list");
		}
		//console.debug(mapFrameCtl.status.isExtendList);

		ifr.showRoadView(map, {'x':_x, 'y':_y});
		callSymbolClickIframe();
	}catch(e){
	//	console.debug(e.message);
	}
}