function $(id) { 
	return document.getElementById(id);
}

function $C(node) {
	return document.createElement(node);
}

function $T(text) {
	return document.createTextNode(text);
}

function $A(iterable)
{
	if (!iterable) return [];
	var results = [];
	for (var i = 0, length = iterable.length; i < length; i++)
	  results.push(iterable[i]);
	return results;
}

Object.extend=function(a, b){
  for (var property in b) a[property] = b[property];
  return a;
};

Function.prototype.bind = function()
{
	var __method = this, args = $A(arguments), object = args.shift();
	return function() {
		return __method.apply(object, args.concat($A(arguments)));
	}
}

Function.prototype.bindAsEventListener = function()
{
	var __method = this, args = $A(arguments), object = args.shift();
	return function(event) {
		return __method.apply(object, [event || window.event].concat(args));
	}
}


//소숫점 잘라주기
function FormatFloat(num,len)
{
	var formatNum = num.toString();
	var dotPos = formatNum.indexOf(".");
	if(dotPos>0) {
		if(formatNum.length - formatNum.indexOf(".") > len) {
			formatNum = formatNum.substr(0,dotPos+len+1);
		} 
		else {
			while(formatNum.length - (len+1) != formatNum.indexOf(".")) formatNum = formatNum.concat("0");
		}
	}
	else {
		formatNum = formatNum.concat(".");
		while(--len>=0) formatNum = formatNum.concat("0");
	}
	return formatNum;
}
//, 붙이기
function FormatNum(num)
{
	if(!num) return "";
	num = num.replace(/[^(0-9)]/gi,"");
	if(num.length == 0 || num.length <4) return num;
		
	var val = num.replace(/,/gi, "");
	var newval = [];
	var first = val.length % 3;
	var loopcnt = Math.floor(val.length / 3);
	while(loopcnt--) {
		newval.push(val.substr(first+loopcnt*3,3));	
	}
	if(first>0) newval.push(val.substr(0,first));
	return newval.reverse().join();
} 


function recentSearch(dataset,id) 
{
	this.area = $(id);
	this.dataset = dataset;
	this.dataCnt = dataset.length;
	this.boxWidth = 100;
	this.liGroup = 3; // 한 화면당 보이는 아이템수
	this.liWidth = parseInt((this.boxWidth-120-2)/3); // 아이템 가로사이즈
	this.liHeight = null; // 아이템 세로사이즈
	this.pos_n = 0;
	this.costUnit = "만원";
	this.direct = "h"; // v/h 세로/가로방향 구분
	this.linkLen = 15;
	this.defaultTxt = "";
	this.setLayout();
	this.area.style.position = "relative";
}

recentSearch.prototype = {
	setParam: function( param ){
		Object.extend( this, param );
	},
	setLayout: function(){
		this.box = $C('DIV'); this.box.id = 'rsCont';  // 컨테이너 영역
		var titleBox = $C('DIV'); titleBox.id = 'rsTitle'; // 제목 영역
		var navBox = $C('DIV'); navBox.id = 'rsNav'; // 네비버튼 영역
		var cntAreaBox = $C('DIV'); cntAreaBox.id = 'rsTitleCnt'; // 제목 내 개수영역
		this.cntArea = $C('SPAN'); this.cntArea.className = "cnt";
		this.listArea = $C('DIV'); this.listArea.id = 'rsListCont'; 
		this.prevBT = $C('A'); this.prevBT.id = 'prevBT'; this.prevBT.href="#"; this.prevBT.onclick = this.prevItem.bind(this);
		this.nextBT = $C('A'); this.nextBT.id = 'nextBT'; this.nextBT.href="#"; this.nextBT.onclick = this.nextItem.bind(this);

		var temp = this.liWidth*this.liGroup + (this.liGroup-1); 
		//this.listArea.style.width = temp+"px";
		//this.box.style.width = (temp+120)+"px"; 

		cntAreaBox.innerHTML = "<strong>최근검색</strong>";
		cntAreaBox.appendChild($T("(")); cntAreaBox.appendChild(this.cntArea); cntAreaBox.appendChild($T(")"));
		titleBox.appendChild(cntAreaBox);
		this.box.appendChild(titleBox);
		this.box.appendChild(this.listArea);
		navBox.appendChild(this.prevBT);
		navBox.appendChild(this.nextBT);
		this.box.appendChild(navBox);
	},
	render : function() {
		this.setCnt(this.dataCnt);
		if(!this.dataset || this.dataCnt == 0) this.noItem();
		else {
			this.ul = $C('UL'); this.ul.id="rsList";
			this.ul.style.position = "relative";
			this.ul.style.top = "0px";
			this.ul.style.left = "0px";
			if( this.direct == "v" ) this.ul.style.width = "100%";

			this.pos = [];
			var costHelp = "";
			if ( this.costUnit != "" ){
				costHelp = "면적당가 ";
			}

			for(var i=0,cnt=this.dataCnt;i<cnt;++i) {
				var li = $C('LI'); li.id = "rsItem"+i;
				if ( this.direct == "v" && this.liHeight != null ){
					li.style.height = this.liHeight+"px";
				} else if ( this.direct == "h" ){
					li.style.width = (this.liWidth-10)+"px";
					
				}
				switch( this.dataset[i].type ){
				case "M"://매물
					if(this.dataset[i].type == 4) this.dataset[i].price = costHelp+FormatNum(this.dataset[i].price)+this.costUnit;
					else this.dataset[i].price = FormatNum(this.dataset[i].price)+this.costUnit;
					var delBT = $C('A'); delBT.className = 'del'; delBT.href="#"; delBT.onclick = this.deleteItem.bind(this,li.id,this.dataset[i].type, this.dataset[i].id);
					var urlLink = $C('A'); urlLink.className = 'rsLink'; urlLink.href = "http://realestate.daum.net/maemul/detail/"+this.dataset[i].id; urlLink.appendChild($T( this.dataset[i].name ));
					//urlLink.onclick = 'gLink(null, "RTES", '+(i+1)+', "1");';
					UI.addEvent( urlLink, "click", this.clicklog.bind(this, i) );
					var areaInfo = $C('SPAN'); areaInfo.className = 'rsArea'; areaInfo.appendChild( $T( ' '+ parseInt(this.dataset[i].size) + '㎡ ' ) );
					var costText = $C('SPAN'); costText.className = 'rsItem t'+this.dataset[i].saletype; costText.innerHTML = this.dataset[i].price;
					li.appendChild(delBT);
					li.appendChild(urlLink);
					li.appendChild(areaInfo);
					li.appendChild(costText);
					if( UI.length( this.dataset[i].name ) <= 10 ){
						li.appendChild($C("BR"));
					}
					this.ul.appendChild(li);

					break;
				case "D"://단지 

					
					if(this.dataset[i].type == 4) this.dataset[i].price = costHelp+FormatNum(this.dataset[i].price)+this.costUnit;
					else this.dataset[i].price = FormatNum(this.dataset[i].price)+this.costUnit;
					var delBT = $C('A'); delBT.className = 'del'; delBT.href="#"; delBT.onclick = this.deleteItem.bind(this,li.id,this.dataset[i].type,this.dataset[i].id);
 
					var urlLink = $C('A'); urlLink.className = 'rsLink'; urlLink.href = "http://realestate.daum.net/maemul/danji/"+this.dataset[i].id+ "/S/summary"; urlLink.appendChild($T( this.dataset[i].name ));
					UI.addEvent( urlLink, "click", this.clicklog.bind(this, i) );
					//UI.addEvent( urlLink, "click", gLink(null, "RTES", i+1, "1") );
					//var areaInfo = $C('SPAN'); areaInfo.className = 'rsArea'; areaInfo.appendChild( $T( ' '+ FormatFloat(this.dataset[i].size,2) + '㎡ ' ) );
					var costText = $C('SPAN'); costText.className = 'rsItem tDanji'; costText.innerHTML = '';
					//urlLink.appendChild(areaInfo);
					li.appendChild(delBT);
					li.appendChild(urlLink);
					li.appendChild(costText);
					li.appendChild($C("BR"));
					if( UI.length( this.dataset[i].name ) <= 10 ){
						li.appendChild($C("BR"));
					}
					//li.appendChild(costText);
					this.ul.appendChild(li);

					break;
				}

					
			}

			this.listArea.appendChild(this.ul);

			this.setCss(this.dataCnt);
			this.setPos(this.dataCnt);
			this.orderItem();
			this.setBT();
		
		}

		if(this.area) this.area.appendChild(this.box);
	},
	clicklog : function( i ){
		return gLink(null, "RTES", i+1, "1");
	},
	noItem : function() {
		if ( this.defaultTxt != "" ){
		this.listArea.innerHTML = '<p class="noItem">'+this.defaultTxt+'</p>';
		}
		//this.area.style.display = "none";
	},
	prevItem : function() {

		if(this.pos_n>0) {
			this.pos_n--;
			this.orderItem();
		}

		this.setBT();
		return false;
	},
	nextItem : function() {
		if(this.pos_n<this.pos.length-1) {
			this.pos_n++;
			this.orderItem();
		}
		this.setBT();
		return false;
	},
	orderItem : function(){
		var objLi = this.ul.childNodes;
		var strNum = this.liGroup*this.pos_n;
		var endNum = strNum+this.liGroup;
		
		for( var i=objLi.length-1; i>=0; i-- ){
			if ( i >= strNum && i < endNum ){
				objLi[i].style.display = "block";
			} else {
				objLi[i].style.display = "none";
			}
		}
	},
	deleteItem: function(lid, mtype, cid) {
		this.ul.removeChild($(lid));
		var reqTemp = new Image();
		reqTemp.src="/maemul/recent/?method=remove&type="+mtype+"&id="+cid;

		reqTemp = null;
		//setCookie("RECENTSEARCH",rSearchCookie.replace(new RegExp("\\|"+cid+"|"+cid+"\\||"+cid,'gi'),""));
		this.setCnt(--this.dataCnt);
		this.setCss(this.dataCnt);
		if(this.pos.length > Math.ceil(this.dataCnt/this.liGroup)) this.pos.pop();
		this.setBT();
		if(this.dataCnt==0) this.noItem();
		else this.orderItem();
		return false;

	},
	setCnt : function(dataCnt) {
		this.cntArea.innerHTML = dataCnt;
	},
	setCss : function(dataCnt) {
		for(var i=0;i<dataCnt;++i) {
			if(i%this.liGroup != (this.liGroup-1) && i< dataCnt-1) this.ul.childNodes[i].className = "gBD";
			else this.ul.childNodes[i].className = "";
		}
	},
	setPos : function(dataCnt) {
		if ( this.direct == "h" ){
			for(var i=0,j=0;i<dataCnt;i=i+this.liGroup,++j) {
				//this.pos[j] = [j*this.liWidth*-1*this.liGroup,0];
				this.pos[j] = [j*this.liHeight*-1*this.liGroup,0];
			}
		} else if ( this.direct == "v" ){
			for(var i=0,j=0;i<dataCnt;i=i+this.liGroup,++j) {
				this.pos[j] = [j*this.liHeight*-1*this.liGroup,0];
			}
		}
	},
	setBT : function() {
		if(this.pos_n <= 0) this.prevBT.className="";
		else this.prevBT.className="on";
		if(this.pos_n >= this.pos.length-1) this.nextBT.className="";
		else this.nextBT.className="on";
	}
}


// 부동산 2.0용 우측 따라다니는 슬라이더
UI.WingSlider = function( option ){
	this.options = {
		smooth : false, // 부드럽게 이동
		baseY : 142, // 최소 높이
		trgY : 147, // 이동할 높이
		checkTime : 500, // 스크롤이벤트 발생 후 함수실행간 시간 ( 밀리초 )
		speed : 0.2, // 이동 스피드 ( 0.0 < speed < 1.0 )
		iTime : 100, // 스크롤 위치감지 interval 시간
		isMoving : false // 이동중 flag
	}
	Object.extend(this.options, option);
	
	this.objWing = UI.$("LaySlideWing");
	if ( this.objWing ){
		UI.addEvent( window, "scroll", this.run.bindAsEventListener(this) );
		this.run();
	}
}
UI.WingSlider.prototype = {
	run : function (){
		if ( this.objWing == null ) return false;
		var brow = UI.getBrowser();
		var pageYOffset = document.documentElement.scrollTop;

		this.options.trgY = pageYOffset; // 최초 목적지 설정
		if ( pageYOffset <= this.options.baseY ){ // 최소 높이보다 적으면 기본값 적용
			this.objWing.style.top = this.options.baseY + "px";
		} else {
			if ( this.options.smooth == false ) { // 이벤트와 동시에 이동
				this.objWing.style.top = pageYOffset + "px";
			} else { // 레이어 부드럽게 이동
				if ( this.options.isMoving == false ){ // 이동중이 아닐때만 1회 실행
					setTimeout( this.smoothMove.bind(this), this.options.checkTime );
					this.options.isMoving = true;
				}
			}
		}
		
	},
	smoothMove : function(){
		var posY = this.objWing.offsetTop; // 현재 높이
		posY += this.options.speed*( this.options.trgY - posY ); // 이동값


		if ( posY < this.options.baseY ){ // 기본높이 고정
			posY = this.options.baseY;
		}

		

		this.objWing.style.top = posY +"px"; 
		if ( posY == this.options.trgY ){ // 이동완료
			this.options.isMoving = false; 
		} else { // 완료가 아니면 재귀호출
			setTimeout( this.smoothMove.bind(this), this.options.itime );
		}
	}
}


// 최근검색 / 평형계산기 스크롤 슬라이더
var pCalcForm = null; // 계산기 전역
function renderWingSlider(){
	var layout = '\
	<h3>최근검색 매물(시세) / 평형 계산기</h3>\
	<div id="LaySlideWing">\
		<div id="RecentBox">\
			<div class="slideBox boxT"></div>\
			<div class="slideBox boxM"><div id="RSAreaT_MS"></div></div>\
			<div class="slideBox boxB"></div>\
		</div>\
		<div id="CalcBox">\
			<div class="slideBox boxT calcTop"><div class="icoCalc fs_small fw_b">평형계산기</div></div>\
			<div class="slideBox boxM">\
				<form name="PyeongCalcForm" id="PyeongCalcForm" action="" onsubmit="pCalcForm.calculate();return false;">\
					<input type="text" value="3.3" id="PCalcM" size="7" class="fs_small" maxlength="20" onfocus="pCalcForm.setFocus(this, \'1\');"> <span id="PCalcUnit">㎡</span>\
					<input type="submit" id="PCalcButton" class="typeBtn" value="< 계산하기 >" onclick="return gLink(null, \'RTES\', \'1\', \'1\');">\
					<input type="text" value="1" id="PCalcP" size="7" class="fs_small" maxlength="15" onfocus="pCalcForm.setFocus(this, \'2\');"> <span id="PCalcUnit">평</span>\
				</form>\
			</div>\
			<div class="slideBox boxB"></div>\
		</div>\
	</div>';

	document.write( layout );
	var RS = new recentSearch(rSearch,'RSAreaT_MS');
	RS.setParam( { liGroup:4, boxWidth:90, liWidth:79, direct:"v", linkLen:10, costUnit:"", defaultTxt:"최근 검색한 항목이 없습니다." } );
	RS.render();

	// 평형 계산기
	pCalcForm = new UI.PyeongCalc("PyeongCalcForm", {text:"PCalcText",result:"PCalcResult",button:"PCalcButton",unit:"PCalcUnit"} );
	var objConTop = UI.$("CON_TOP");
	var url = document.location.href;

	if( url.indexOf( "realestate.daum.net/search/" ) > -1 ){
		var posTop = "174";
		try{
			posTop = UI.$("CONTENTS").offsetTop + UI.$("SearchMenu").offsetTop;
		}catch (e){}
	} else if ( objConTop == null ){
		var posTop = "117";
	} else if ( objConTop.className == "typeMap" ){
		var posTop = "146";
	} else if ( objConTop.className == "typeComplex" ){
		var posTop = "117";
	} else if ( objConTop.className == "typeNoMap" ){
		var posTop = "146";
	} else {
		var posTop = "117";
	}

	new UI.WingSlider( {smooth:true,baseY:posTop,trgY:posTop} );
};



/* 평형자동계산기 */
UI.PyeongCalc = function( formId, userObjId ){
	this.form = UI.$( formId );
	this.focusObj = null; // 포커스된 입력박스
	this.objId = {
		inputM:"PCalcM",
		inputP:"PCalcP"
	}
	this.prevValue = [];

	Object.extend(this.objId, userObjId);

	this.objInputM = UI.$( this.objId.inputM );
	this.objInputP = UI.$( this.objId.inputP );
	this.objInputM.setAttribute("autocomplete","off");
	this.objInputP.setAttribute("autocomplete","off");
}
UI.PyeongCalc.prototype = {
	calculate : function(){
		var elseObj = null;
		var outVal = null;
		if ( this.focusObj == null ){
			this.objInputM.focus();
			return false;
		} else {
			if ( this.focusObj.id == this.objId.inputM ){
				elseObj = this.objInputP;
			} else {
				elseObj = this.objInputM;
			}
		}

		if ( this.prevValue[0] == this.objInputM.value && this.prevValue[1] == this.objInputP.value ){
			this.objInputM.value = "";
			this.objInputP.value = "";			
			this.focusObj.focus();
			return false;
		}

		var match = this.focusObj.value.match(/^([0-9,.]+)$/);
		if( this.focusObj.value == "" ){
			alert( "값을 입력해 주세요");
			this.focusObj.select();
			this.focusObj.focus();
			return false;
		} else if( match == null ){
			alert( "잘못된 입력 형식입니다");
			this.focusObj.select();
			this.focusObj.focus();
			return false;
		}
		var inVal = parseFloat( this.focusObj.value.replace(/[^.0-9]*/gi , "" ) );
		if ( isNaN( inVal ) == true ) {
			elseObj.value = "";
			this.focusObj.select();
			this.focusObj.focus();
			return false;
		}

		if ( this.focusObj.id == this.objId.inputM ){
			//㎡ -> 평
			outVal = Math.round(inVal * 0.3025 * 100) / 100;
			this.objInputP.value = UI.addComma( outVal );
		} else {
			//평 -> ㎡
			outVal = Math.round(inVal * 3.3058 * 100) / 100; 
			this.objInputM.value = UI.addComma( outVal );
		}
		this.focusObj.value = UI.addComma( this.focusObj.value );
		this.focusObj.select();
		this.focusObj.focus();
		this.prevValue = [ this.objInputM.value, this.objInputP.value ];
	},
	setFocus : function( obj, type ){
		obj.select();
		if( (type=="1" && obj.value =="3.3") || (type=="2" && obj.value == "1") ){
			obj.value = "";
		}	
		this.focusObj = obj;
	}
};
