/****************************************************************************/
//		 ÀÚµ¿°Ë»ö Client Script
/****************************************************************************/

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  net.currentLoader=this;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}


net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  try{var httpStatus=req.status;
  if (ready==net.READY_STATE_COMPLETE){
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      this.onerror.call(this);
    }
  }
  }
  catch(e){}
}

net.ContentLoader.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.req.readyState
    +"\nstatus: "+this.req.status
    +"\nheaders: "+this.req.getAllResponseHeaders());
}





/*===================================================*/



//Listing 10.6
function SetProperties(
			xElem,
			xHidden,
			xserverCode,
			xignoreCase,
			xmatchAnywhere,
			xmatchTextBoxWidth,
			xshowNoMatchMessage,
			xnoMatchingDataMessage,
			xuseTimeout,
			xtheVisibleTime
			)
{
	var props	 = {
				elem			: xElem,
				hidden			: xHidden,
				serverCode		: xserverCode,
				regExFlags		: ( (xignoreCase) ? "i" : "" ),
				regExAny		: ( (xmatchAnywhere) ? "" : "^" ),
				matchAnywhere		: xmatchAnywhere,
				matchTextBoxWidth	: xmatchTextBoxWidth,
				theVisibleTime		: xtheVisibleTime,
				showNoMatchMessage	: xshowNoMatchMessage,
				noMatchingDataMessage	: xnoMatchingDataMessage,
				useTimeout		: xuseTimeout
			};

	AddHandler(xElem);
	return props;
}

//Listing  10.8
var isOpera	= (navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
function AddHandler(objText)
{
	objText.onkeyup		= function() { GiveOptions('up'); };
	objText.onkeydown	= function() { GiveOptions('down'); };
	objText.onblur	= function(){
		if (this.obj.useTimeout)	{ StartTimeout(); }

	}
	if (isOpera)	{ objText.onkeypress = GiveOptions; }
}

//Listing 10.9
var arrOptions			= new Array();
var strLastValue		= "";
var bMadeRequest;
var theTextBox;
var objLastActive;
var currentValueSelected	= -1;
var bNoResults			= false;
var isTiming			= false;
var $curSelectedFocus		= 1;	//ÀÚµ¿°Ë»öÃ¢ Æ÷Ä¿½º À§Ä¡
var $tboxSize			= 5;

//Listing 10.10
function GiveOptions(e)
{
	var intKey	= -1;	//»ç¿ëÀÚ°¡ ´­¸¥ Å°°ª

	if (window.event)
	{
		intKey		= event.keyCode;
		theTextBox	= event.srcElement;
	}
	else
	{
		intKey		= e.which;
		theTextBox	= e.target;
	}

	//½Ã°£ Á¦ÇÑ Å¸ÀÌ¸Ó ÃÊ±âÈ­
	if (theTextBox.obj.useTimeout)
	{
		if (isTiming)	{ EraseTimeout(); }	//¸¹Àº Á¢¼ÓÀÚ ´ëºñ
		StartTimeout();
	}

	//ÅØ½ºÆ® ÀÔ·ÂÃ¢¿¡ ÀÔ·ÂµÈ ³»¿ë ÀÖ´ÂÁö È®ÀÎ

	if (theTextBox.value.length == 0 && !isOpera )
	{
		arrOptions	= new Array();
		HideTheBox();
		strLastValue	= "";
		//return false;
	}

	//±â´ÉÅ° µ¿ÀÛ
	if (objLastActive == theTextBox && e == 'down')
	{

		if	(intKey == 13)//¿£ÅÍÅ° ÀÔ·Â½Ã ¹ß»ý
		{
			GrabHighlighted(true);
			//theTextBox.blur();
			return false;
		}
		else if	(intKey == 38)	//up
		{
			//alert('up');
			MoveHighlight(-1);
			GrabHighlighted(false);
			return false;
		}
		else if	(intKey == 40)	//dn
		{
			//alert('dn')
			MoveHighlight(1);
			GrabHighlighted(false);
			return false;
		}
		else	{}
	}


	//Å° ÀÔ·Â ³»¿ë Ã³¸®
	if	(	(objLastActive != theTextBox) ||
			(theTextBox.value.indexOf(strLastValue) != 0) ||
			((arrOptions.length==0 || arrOptions.length==15) && !bNoResults) ||
			(theTextBox.value.length <= strLastValue.length)
		)
	{

		objLastActive	= theTextBox;
		bMadeRequest	= true;
		if ((intKey == 8) || e == 'down')
		{
			//°Ë»ö¾î°¡ ¿µ¹®+¼ýÀÚÀÎ°æ¿ì, shift keyÁ¦¿Ü
			if ((intKey != 8) && (intKey < 229) && (intKey != 16))
			{
				TypeAhead(String.fromCharCode(intKey));
			}
			//ÇÑ±ÛÀÏ°æ¿ì
			else
			{
				TypeAhead(theTextBox.value);
			}
		}
	}
	else if (!bMadeRequest)
	{
		//°Ë»öÃ¢¿¡¼­ ¹æÇâÅ° ¿òÁ÷ÀÌÁö ¾ÊÀ»°æ¿ì¸¸
		if (e == 'up' && intKey!=40 && intKey!=40)
		{
			BuildList(theTextBox.value);
		}

	}


	//ÀÔ·ÂµÈ ³»¿ë º¸°ü
	strLastValue	= theTextBox.value;

}

//Listing 10.11
//ÀÔ·Â°ª Àü¼ÛºÎºÐ
function TypeAhead(xStrText)
{
	//alert(xStrText);

	var strParams	= "q=" + xStrText
			+ "&where="
			+ theTextBox.obj.matchAnywhere;

	//alert(strParams);

	var loader1	= new net.ContentLoader(
						theTextBox.obj.serverCode,	//url
                                    		BuildChoices,			//callback function
                                    		null,				//onerror function
                                    		"POST",
                                    		strParams
                                    		);
}

//Listing 10.12
//AjaxÅë½Å ¼º°ø½Ã
function BuildChoices()
{
	var strText	= this.req.responseText;
	eval(strText);		//JSON Data
	BuildList(strLastValue);
	bMadeRequest	= false;
}

//Listing 10.13
//°á°ú¸ñ·Ï Ç¥½Ã
function BuildList(theText)
{
	SetElementPosition(theTextBox);
	var theMatches	= MakeMatches(theText);
	mLen	= theMatches.length;
	theMatches	= theMatches.join().replace(/\,/gi,"");
	if (theMatches.length > 0)
	{
		$("spanOutput").innerHTML	= theMatches;
		$("OptionsList_0").className	= "spanHighElement";
		if (mLen <= $tboxSize)
		{
			$('spanOutput').style.height	= mLen*19;
			$('spanOutput').style.overflow	= "visible";
		}
		else
		{
			$('spanOutput').style.height	= $tboxSize*19;
			$('spanOutput').style.overflow	= "scroll";
			$('spanOutput').style.overflowX	= "hidden";
		}
		currentValueSelected	= 0;
		bNoResults		= false;
	}
        else
        {
		currentValueSelected = -1;
		bNoResults = true;
		//°Ë»ö°ª¾øÀ»½Ã ¸Þ¼¼Áö Ç¥½Ã¸¦ ¿øÇÑ´Ù¸é
		if (theTextBox.obj.showNoMatchMessage)
		{
			document.getElementById("spanOutput").innerHTML	= "<span class='noMatchData'>"
									+ theTextBox.obj.noMatchingDataMessage
									+ "</span>";
		}
		else
		{
			HideTheBox();
		}
        }
}

//Listing 10.14
function SetElementPosition(theTextBoxInt){
	var selectedPosX	= 0;
	var selectedPosY	= 0;
	var theElement		= theTextBoxInt;
	if (!theElement)	{ return; }
	var theElemHeight	= theElement.offsetHeight;
	var theElemWidth	= theElement.offsetWidth;
	while(theElement != null)
	{
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
	xPosElement		= document.getElementById("spanOutput");
	xPosElement.style.left	= selectedPosX;

	if (theTextBoxInt.obj.matchTextBoxWidth)
	{
		xPosElement.style.width = theElemWidth;
	}

	xPosElement.style.top		= selectedPosY + theElemHeight
	xPosElement.style.display	= "block";

	if(theTextBoxInt.obj.useTimeout)
	{
		xPosElement.onmouseout = StartTimeout;
		xPosElement.onmouseover = EraseTimeout;
	}
	else
	{
		xPosElement.onmouseout = null;
		xPosElement.onmouseover = null;
	}
}

//Listing 10.15
var countForId = 0;


//°á°ú ¸ñ·Ï³»¿ëÀ» ¹è¿­¿¡ ³Ö¾î¼­ ¸®ÅÏ
function MakeMatches(xCompareStr){
	countForId	= 0;
	var matchArray	= new Array();
	var regExp	= new RegExp(theTextBox.obj.regExAny + xCompareStr, theTextBox.obj.regExFlags);

	for (i = 0; i < arrOptions.length; i++)
	{
		var theMatch = arrOptions[i][0].match(regExp);
		if (theMatch)
		{
			matchArray[matchArray.length]	= CreateUnderline(arrOptions[i][0], xCompareStr, i);
		}
	}
	//alert(matchArray.length);
	return matchArray;
}


//Listing 10.16
var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";
var selectSpanStart = "<table width='100%' cellpadding='0' cellspacing='0'><tr valign='middle'><td style='width:100%;display:block;cursor:hand;' class='spanNormalElement' onmouseover='SetHighColor(this)'  ";
var selectSpanEnd ="</td></tr></table>";

function CreateUnderline(xStr,xTextMatch,xVal)
{
	selectSpanMid	= "onclick='SetText(" + xVal + "); location.href=\"/search/?ctr=list_view&sVal=\"+ arrOptions["+xVal+"][0]' "  +
				"id='OptionsList_" +
				countForId + "' theArrayNumber='"+ xVal +"'>";
	var regExp	= new RegExp(theTextBox.obj.regExAny + xTextMatch,theTextBox.obj.regExFlags);
	var aStart	= xStr.search(regExp);
	var matchedText = xStr.substring(aStart, aStart + xTextMatch.length);
	countForId++;
	var rValue	= selectSpanStart + selectSpanMid + xStr.replace(regExp,undeStart + matchedText + undeEnd) + selectSpanEnd;
	return rValue;
}

//Listing 10.17
function MoveHighlight(xDir)
{
	if (currentValueSelected >= 0)
	{
		newValue	= parseInt(currentValueSelected) + parseInt(xDir);
		if (newValue > -1 && newValue < countForId)
		{
			currentValueSelected = newValue;
			SetHighColor (null);
		}
	}
	//alert(newValue);


	//dn
	if ((xDir==1) && (countForId-1) != currentValueSelected)
	{
		$curSelectedFocus	= ($curSelectedFocus)+1;
		//alert('dn');
		//¹ØÀ¸·Î ½ºÅ©·ÑÇÒ °ø°£ÀÌ ÀÖ´Â°æ¿ì Æ÷Ä¿½º À§Ä¡ ÃÊ±âÈ­
		if ($curSelectedFocus > $tboxSize && (currentValueSelected<=countForId))
		{
			spanOutput.doScroll('scrollbarDown');
			spanOutput.doScroll('scrollbarDown');
			//spanOutput.doScroll('scrollbarDown');

			//spanOutput.doScroll('scrollbarDown');
			$curSelectedFocus	= $tboxSize;
		}
	}
	//up
	if ((xDir==-1) && (currentValueSelected >= 0))
	{
		//alert(curSelectedFocus);
		//ÇöÀç Æ÷Ä¿½º°¡ 1ÀÌ¸é¼­ À­ÂÊÀ¸·Î ½ºÅ©·Ñ °ø°£ÀÌ ÀÖ´Â°æ¿ì
		if ($curSelectedFocus <= 1)
		{
			//$curSelectedFocus = 5;

			spanOutput.doScroll('scrollbarUp');
			spanOutput.doScroll('scrollbarUp');
			//spanOutput.doScroll('scrollbarUp');
			//spanOutput.doScroll('scrollbarUp');
		}
		//±×¿Ü
		else if ($curSelectedFocus > 1)
		{
			$curSelectedFocus	= ($curSelectedFocus)-1;
		}

	}
	//alert("ccurrentValueSelected="+currentValueSelected + "\ncountForId=" + countForId + "\ncurSelectedFocus=" + $curSelectedFocus + "\ntboxSize="+$tboxSize);
	//alert(currentValueSelected+"/"+ (currentValueSelected%$tboxSize));
}

function SetHighColor(theTextBox)
{
	if (theTextBox)
	{
		currentValueSelected =
					theTextBox.id.slice(theTextBox.id.indexOf("_")+1,
					theTextBox.id.length);
	}

	for (i = 0; i < countForId; i++)
	{
		document.getElementById('OptionsList_' + i).className =
		'spanNormalElement';
	}
	document.getElementById('OptionsList_' + currentValueSelected).className = 'spanHighElement';
}

//Listing 10.18
function SetText(xVal, isHide)
{	//alert(isHide);
	theTextBox.value = arrOptions[xVal][0]; //set text value
	theTextBox.obj.hidden.value = arrOptions[xVal][1];
	var disp	= (isHide) ? "none" : "block";
	document.getElementById("spanOutput").style.display = disp;
	//currentValueSelected = -1; //remove the selected index
}

//°Ë»ö¾î ¼±ÅÃ½Ã ¹ß»ý
function GrabHighlighted(isHide){
	if (currentValueSelected >= 0)
	{
		xVal = document.getElementById("OptionsList_" +	currentValueSelected).getAttribute("theArrayNumber");
		if (!isHide)	{ SetText(xVal, isHide); }
		else 		{ HideTheBox(); }
	}
}

function HideTheBox()
{
	document.getElementById("spanOutput").style.display = "none";
	currentValueSelected = -1;
	EraseTimeout();
}

//Listing 10.19
function EraseTimeout(){
	clearTimeout(isTiming);
	isTiming = false;
}

function StartTimeout(){
	isTiming = setTimeout("HideTheBox()",
	theTextBox.obj.theVisibleTime);
}

