/***** 추천(Suggest text) 관련 Function	***/

var theTextBox;					//텍스트 박스 객체
var currentValueSelected = 0;	//선택된 위치 인덱스
var strLastValue = "";			//검색 단어 임시 저장
var resultCnt = "0";			//결과 값 개수 저장
var bMadeRequest;
var tempVar = "";

//서제스트창 이벤트 함수 연결
function initSuggestEvent(tid){
	$(tid).onfocus = initSuggestList;
	if(bIE) $(tid).onkeyup = suggestEvent;
	else $(tid).onkeypress = suggestAtFF;

	$(tid).onkeydown = MovingHighlight;
	$(tid).onblur = hideList;
	hideSuggestDiv(tid);
}

//포커스가 올 때 기본 검색 세팅
function initSuggestList(e){
	if(window.event)
	  theTextBox = event.srcElement;
	else
	  theTextBox = e.target;
	
	if( theTextBox.value.length == 0 )
		$(theTextBox.id).value = '';
	else
		sendSuggest(theTextBox.id);	
}

//서제스트창 이벤트 함수
function suggestEvent(e){
	var intKey = -1;

	if(window.event){
	  intKey = event.keyCode;
	  theTextBox = event.srcElement;
	}
	else{
	  intKey = e.which;
	  theTextBox = e.target;
	}

	if(intKey == 13){
		//이곳에다가 엔터쳤을 때 해야할 함수들을 id 별로 입력하세요.
		switch (theTextBox.id) {
			case "txtTrafficStart":
				doSearch($("txtTrafficStart"), "S");
				break;
			case "txtTrafficEnd":
				doSearch($("txtTrafficEnd"), "E");
				break;
			case "txtBusNumber":
				doSearch($("txtBusNumber"), "N");
				break;
			case "txtBusStation":
				doSearch($("txtBusStation"), "B");
				break;
			case "txtSubwayStart":
				doSearch($("txtSubwayStart"), "MS");
				break;
			case "txtSubwayEnd":
				doSearch($("txtSubwayEnd"), "ME");
				break;															
		}
		return false;
	}
	else if(intKey == 229 || intKey == 40 || intKey == 38){
		return false;
	}
	
	if( theTextBox.value.indexOf(strLastValue) != 0 || (trim(theTextBox.value)).length != (trim(strLastValue)).length )
	{
		sendSuggest(theTextBox.id);				
		bMadeRequest = true;
	}
}

//FF 용 함수, 보강 필요함
function suggestAtFF() {
	if(bIE) return;
	if (tempVar != $(theTextBox.id).value) {
		sendSuggest(theTextBox.id);
		tempVar = $(theTextBox.id).value;
	} else {
	}
	setTimeout("suggestAtFF()", 10);
}

//서제스트 텍스트 창에서 계속 누르고 있는 경우
function MovingHighlight(e){
	var intKey = -1;
	if(window.event){
	  intKey = event.keyCode;
	  theTextBox = event.srcElement;
	}
	else{
	  intKey = e.which;
	  theTextBox = e.target;
	}

	if(intKey == 38){
		MoveHighlight(-1, theTextBox);
		return false;
	}
	else if(intKey == 40){
		MoveHighlight(1, theTextBox);
		return false;	
	}
}	

//선택한 서제스트 항목 위/아래 이동
function MoveHighlight(idx, obj){
	//전체 데이터 개수 가져오기
	if(resultCnt == "0" || resultCnt == 0 ) return;

	var strLineName;
	var strDataName;

	strLineName = "sgItem_";
	strDataName = "suggest_data";	
		
	if(idx == "1" && currentValueSelected < resultCnt)  currentValueSelected++; 
	else if(idx == "-1" && currentValueSelected > 0)  currentValueSelected--; 

    //선택한 줄은 하이포맷으로  
    for(var k = 1; k <= resultCnt; k++)
    	$(strLineName+k).style.background = "#fff";

   	if(currentValueSelected >= 1 && currentValueSelected <= resultCnt){
   		selectRow = $(strLineName+currentValueSelected);  	
  		selectRow.style.background = '#f8f4f0';
  		//텍스트 박스에 선택한 내용 자동 세팅
  		obj.value = selectRow.innerHTML;
  	}

    //위, 아래로 이동시 일정 간격마다 스크롤 자동 조절
	if( parseInt((currentValueSelected) - 1) % 5 == 0 && idx == "1")
		$(strDataName).scrollTop = currentValueSelected * 18 - 18;
	else if( parseInt((currentValueSelected) - 1) % 5 == 4 && idx == "-1")
		$(strDataName).scrollTop = currentValueSelected * 18 - 90;
		
	//작업 후에 다시 이벤트를 받기 위해 텍스트창에 포커스 주기	  		
	obj.focus();			
}

//포커스가 올 때 기본 검색 세팅
function hideList(e){
	if(window.event)
	  theTextBox = event.srcElement;
	else
	  theTextBox = e.target;

	setTimeout(function(){hideSuggestDiv(theTextBox.id)}, 300);
}	

//ajax로 데이터 요청
function sendSuggest(id)
{	
	strLastValue = $(id).value;		
	if(strLastValue == "") return;

	var url = "/traffic/search.map";
	var pars = "cmd=suggest&TEXT=" + encodeURIComponent(strLastValue) + "&LCode=" + getSearchFlag() + "&CID=" + cId;

	ajaxSend(url,pars,function(res){
		currentValueSelected = 0;
		$(id + "ResultLayer").innerHTML=res.responseText;	
		showSuggestDiv(id);	
	});
}	
		
//서제스트 영역 보여주기
function showSuggestDiv(id) {
	//서제스트 결과값의 수를 전역 변수에 세팅한다.
	resultCnt = $("sugItemCount").value;
	if( ($(id).value == '' || $(id).value.length == 0  ) &&  resultCnt == "0"){
		$(id).focus();
		$(id).value = '';
	}

	if(resultCnt == "0" || resultCnt == 0) { hideSuggestDiv(id); return; }

	//결과 레이어를 보여준다.
	$(id + "ResultLayer").style.display="";
	
	//결과가 나올 때 처리해야 할 예외사항을 작성한다.
	if(id == "txtTrafficStart"){
		$("txtTrafficEndResultLayer").style.display="none";
	}
	else if(id == "txtTrafficEnd"){
		$("txtTrafficStartResultLayer").style.display="none";
	}

}

//서제스트 영역 감추기
function hideSuggestDiv(id) {
	if($(id) == null  || $(id+"ResultLayer") == null) return;
	
	var sugResultDiv = $(id+"ResultLayer");
	currentValueSelected = 0;
	sugResultDiv.style.display="none";
	sugResultDiv.innerHTML = "";
	
	//가려도 결과를 남겨야 할까 두어야 할까?
	resultCnt = 0;	
}

//서제스트 클릭 후 동작
function setSuggestValue( value )
{
	if(theTextBox == null ) return;
	//textbox에 데이터를 세팅하고,
	theTextBox.value = value;
	//서제스트 결과 영역을 닫는다.
	hideSuggestDiv(theTextBox.id);
}
