var g_EObjects;

function eAddObj(textBoxID, jsAutoSuggestBox)
{
	if (typeof(g_EObjects) == "undefined")
		g_EObjects=new Array();
			
	g_EObjects[textBoxID]=jsAutoSuggestBox;
}

function HiddenAll()
{	
	for(var obj in g_EObjects)
	{
		try
		{
			g_EObjects[obj].HideDiv();
		}
		catch(err)
		{
		
		}
	}
 
}

function HideOthers(objName)
{
	for(var obj in g_EObjects)
	{
		if(obj != objName )
		{	
			try
			{
				g_EObjects[obj].HideDiv();
			}
			catch(err)
			{
			
			}
		}
	}	
}


function eGetObj(textBoxID)
{
	//JSAutoSuggestBox.TRACE("eGetObj : " + g_ASBObjects[textBoxID]._textBoxID);
	return g_EObjects[textBoxID];
}

function JSAutoSuggestBox()
{ 
///public  
    var dataType;
    var language;
    var selectInputid;
    
    var mnMaxSuggestChars;
    var mnStartSearchIndex;    
    var mnKeyPressDelay;
    
    var msResourcesDir;
    
    var selItemCSSClass;
    var itemCSSClass ;
     
	var CallBack;//回调函数
	
	this.PosTop = -1;
	this.PosLeft = -1;
	this.ClueWidth = 260;
	this.ClueHeight = 140;
	this.ClueAllWidth = 232;
	this.ClueAllHeight = 190;

    ///the lastest outside div   
    var clueBaseDivID ;
    this.GetClueBaseDiv=GetClueBaseDiv;
    
    function GetClueBaseDiv()
	{
		return document.getElementById(this.clueBaseDivID);
	}
    
    
    
    
    
    
    
    //the name input,OnClick,OnKeyUp 
    var textBoxID;
    
    this.GetTextBoxCtrl = GetTextBoxCtrl;
    function GetTextBoxCtrl()
	{
		return document.getElementById(this.textBoxID);
	}
	
	this.GetTextBoxValue = GetTextBoxValue
	function GetTextBoxValue()
	{
	    var txtCtrl=this.GetTextBoxCtrl();
		return(txtCtrl.value);	    
	}
	
	this.SetSelectedValue = SetSelectedValue;
	function SetSelectedValue(value)
	{
	    TRACE("SetSelectedValue: " + value);
		
		
		var hdnSelectedValue=document.getElementById(this.selectInputid);
		//alert(this.selectInputid+ " before value = "+hdnSelectedValue.value);
		hdnSelectedValue.value=value;   
		//alert(this.selectInputid+ " after value = "+hdnSelectedValue.value);
	}
	
	this.SetTextBoxValue = SetTextBoxValue ;
	function SetTextBoxValue()
	{
		var item=this.GetSelItemDiv();
			
		if(item)
		{
			var value=item.getAttribute('value');
					
			TRACE("SetTextBoxValue : Set selected item to " + value);
		
			//Set selected value of control to the value of selected menu item
			this.SetSelectedValue(value);
				
			var txtCtrl=this.GetTextBoxCtrl();
			txtCtrl.value = GetInnerHtml(item);
			
			if( this.CallBack!=null)
				this.CallBack();
		}
		
	}
	
	this.SetParentTextBoxValue = SetParentTextBoxValue ;
	function SetParentTextBoxValue()
	{
		//alert("dddd");
		var item=this.GetSelItemDiv();
			
		if(item)
		{
			var value=item.getAttribute('value');
			TRACE("SetTextBoxValue : Set selected item to " + value);
		
			//Set selected value of control to the value of selected menu item	
	        var hdnSelectedValue=window.parent.document.getElementById(this.selectInputid);
		    hdnSelectedValue.value=value;   
				
			var txtCtrl=window.parent.document.getElementById(this.textBoxID);
			txtCtrl.value = GetInnerHtml(item);
			
			if( this.CallBack!=null)
				this.CallBack();
		}
		
	}
	
	
    
    //show the basecluediv 
    this.ShowDiv=ShowDiv;
    function ShowDiv(sDivContent)
    {
		if(document.getElementById(this.selectInputid + "_err") != null)
		{
			document.getElementById(this.selectInputid + "_err").style.visibility = 'hidden';
		}
    
        this.MoveDivIfAbsolutePos();  
        var clueDiv=this.GetClueBaseDiv();
        
       
        var sInnerHtml;
       
       	if (IsIE()) 
		{	
			
		sInnerHtml = "<div id='" + this.textBoxID + "_content'>";
		sInnerHtml += sDivContent;
		sInnerHtml += "</div>";
		
		var sBlankPage= "Blank.html";	
		sInnerHtml += "<iframe id=\"" + this.textBoxID + "_iframe\" style=\"position:absolute; top:0px; left:0px;\" src=\"\" frameborder=\"0\" scrolling=\"no\"></iframe>";

		}
		else
		{			
		    sInnerHtml=sDivContent;
		}
		
		clueDiv.innerHTML = sInnerHtml;
		
		if (IsIE())	
		{
	    
	 //   var divContent =document.getElementById(this.clueBaseDivID);
		var divContent =document.getElementById(this.textBoxID+"_content");
		divContent.className ="clueBase";
		clueDiv.style.border = 'none';
		clueDiv.style.height= this.ClueHeight + "px";
			
		var divIframe = document.getElementById(this.textBoxID + "_iframe");
			    
	    divIframe.style.width =(divContent.offsetWidth) + 'px';
		divIframe.style.height =(divContent.offsetHeight) + 'px';
        divIframe.style.zIndex = divContent.style.zIndex - 1;
        }
        else
        {
			
        }
        
       
        clueDiv.style.visibility = 'visible';
                                      
    }
    
    //hide the basecluediv  
    this.HideDiv=HideDiv;
    function  HideDiv()
    {   
        var cluebase = this.GetClueBaseDiv();
        if (cluebase!=null)     
        cluebase.style.visibility = 'hidden';
		this.selItemIndex=0;            
    }
    
    this.HideIFrameDiv = HideIFrameDiv ;
    function HideIFrameDiv()
    {
        TRACE("HideIFrameDiv");
        document.getElementById(this.textBoxID+"_CallFrame").style.display="none";      
        this.HideDiv();
    }
      
    
///Event
    
    this.OnAllDataClick = OnAllDataClick ;
    function OnAllDataClick(evt)
    {
        var txtCtrl=this.GetTextBoxCtrl();		
		var divClue=this.GetClueBaseDiv();
		this.mbHasFocus=true ;
		
		var strTop="Top20",strAll="All City";
		
		if(this.language=="cn")
		{
			strTop = "热门城市";
		}
		
		if(this.language=="cn")
		{
			strAll = "所有城市";
		}
		
		var strUrl=this.msResourcesDir;
		var rn  = Math.random();
		strUrl += "DataOutPut.aspx";		
		strUrl += "?language=" + escape(this.language);
		strUrl += "&dataType="+escape(this.dataType);			    
		strUrl += "&textBoxID="+escape(this.textBoxID);
		strUrl += "&selectInputid="+escape(this.selectInputid);
		strUrl += "&BoxType="+escape("all");
		strUrl += "&ItemCSSClass="+escape(this.itemCSSClass) ;
		strUrl += "&clueboxid="+escape(this.clueBaseDivID) ;
		strUrl += "& rn=" + escape( rn);		
		
		var innerHtml="";
		innerHtml += "<table width=\"100%\" class=\""+this.itemCSSClass+"\"><tr>";
		innerHtml += "<td height='26px;'>&nbsp;<u class=\"LinkClick\" onclick=\"eGetObj('"+this.textBoxID+"').OnButtonClick()\">"+strTop;
		innerHtml += "</u>&nbsp;<span style='color:#FF8506;' class=\"ClueTitle\" >["+strAll+"]</span></td>";
		innerHtml += "<td align=right><img onclick=\"eGetObj('"+ this.textBoxID +"').HideIFrameDiv()\" src=\"images/close.gif\" />";
		innerHtml += "</td></tr><tr><td style='vertical-align:top;' algin=\"center\" colspan=\"2\"><div  class=\"clueBr\"></div>";
		innerHtml += "<iframe frameborder=0 width=\"100%\" class=\"iframe\"  id=\""+ this.textBoxID +"_CallFrame\" name=\""+ this.textBoxID  +"_CallFrame\" src=\""+strUrl+"\" ></iframe>";
		innerHtml += "</td></tr></table>" ;
		
		divClue.style.width=  this.ClueAllWidth + "px";
		divClue.style.height= this.ClueAllHeight + "px";
		
		this.ShowDiv(innerHtml);
		
		if( evt.stopPropagation )   evt.stopPropagation();
	
		/*		
		var wcf = document.getElementById(this.textBoxID + "_CallFrame");
	
		if( this.CallBack!=null)
		{
			wcf.callback=this.CallBack;
			alert(wcf.cal);
			
		}
		*/
	
		
    }
    
   
    this.ClearText = ClearText;
    function ClearText()
    {
			TRACE("ClearText");
			document.getElementById(this.textBoxID).select();
			//document.getElementById(this.textBoxID).value = "";
    }
    
    this.OnButtonClick = OnButtonClick;
    function OnButtonClick()
    {    		
		var divClue=this.GetClueBaseDiv();
		this.mbHasFocus=true ;
		if(this.language=="cn")
			divClue.style.width = this.ClueWidth + "px";
		else divClue.style.width = "360px";//(this.ClueWidth + 60) + "px";
		
		var sUrl;
		var rn = Math.random();
		
		sUrl=this.msResourcesDir+"DataOutPut.aspx"+
			    "?language=" + escape(this.language)+
			    "&dataType="+escape(this.dataType)+			    
			    "&textBoxID="+escape(this.textBoxID)+
			    "&BoxType="+escape("CLUE")+
			    "&ItemCSSClass="+escape("item") + 
			    "& rn=" + escape( rn );	
		
        //DataInit	
		var func="eGetObj('" + this.textBoxID + "').GetDataFromServer('" + sUrl + "')";
		TRACE("OnButtonClick : " + func);
		
		//Set timer to update div.  If user types quickly return suggestions when he stops.  					
		divClue.timer = window.setTimeout(func, this.keyPressDelay);
          
    }
    
    this.OnBlur = OnBlur;
    function OnBlur()
    { 
		TRACE("OnBlur");
        if(!this.mbHasFocus)
        {	
		this.HideDiv();
		this.mbHasFocus = false;
		}
    }
    
    this.OnKeyPress = OnKeyPress;
    function OnKeyPress(evt)
	{
		TRACE("OnKeyPress : " + this.GetKey(evt));
		if ((this.GetKey(evt) == 13) && (this.mbCancelSubmit)) 
		{
			return false;
		}
			
		return true;
	}
	
	this.OnKeyUp = OnKeyUp ;
    function OnKeyUp(evt)
    {
        var nKey;
		nKey=this.GetKey(evt);
		
		TRACE("OnKeyUp : " + nKey);
		
		
		//Skip up/down/enter
		if ((nKey!=38) && (nKey!=40) && (nKey!=13))
		{
			var sNewValue;
			sNewValue=this.GetTextBoxValue();
			
			
			if ((sNewValue.length <= this.mnMaxSuggestChars) )
			{
				TRACE("OnKeyUp : Getting data for '" + sNewValue + "'");
				
				var clueMenu = this.GetClueBaseDiv();
				if (clueMenu.timer) window.clearTimeout(clueMenu.timer);
				if(IsIE())
				{
				clueMenu.style.width="0px";
				}
				
				
				//Add escape char to single quote
			//	sNewValue=sNewValue.replace(/\'/, "\\\'").replace(/(^\s*)|(\s*$)/g, "");	
				sNewValue=sNewValue.replace(/\'/, "\\\'").replace(/\s*/g,"");
				TRACE("sNewValue:"+sNewValue);	
				
				if(this.LessChar(sNewValue,this))	return ; 	
				
				if(sNewValue.length>0)
				{
					//set the sUrl
					var sUrl;
					var rn = Math.random();
					sUrl=this.msResourcesDir+"DataOutPut.aspx"+
						"?language=" + escape(this.language)+
						"&dataType="+escape(this.dataType)+
						"&keyword="+escape(sNewValue)+
						"&textBoxID="+escape(this.textBoxID)+
						"&BoxType="+escape("MENU")+
						"&ItemCSSClass="+escape("item") +
						"&rn=" + escape( rn );
					TRACE("sURL: " + sUrl);
					//Set timer to update div.  If user types quickly return suggestions when he stops.  
					var sFunc="eGetObj('" + this.textBoxID + "').GetDataFromServer('" + sUrl + "')";
					TRACE("OnKeyUp : " + sFunc);
					
					this.mnKeyPressDelay = (this.mnKeyPressDelay > 100 ? 100 : this.mnKeyPressDelay);
					clueMenu.timer = window.setTimeout(sFunc, this.mnKeyPressDelay);
				}
			}
		
			if (this.msOldTextBoxValue!=sNewValue)
			{
				this.SetSelectedValue("");
			}
		}     
    }
    
    
	
    this.OnKeyDown = OnKeyDown;
    function OnKeyDown(evt)
    {
      //Indicate that control has focus
		this.mbHasFocus=true;
		
		//Save current text box value before key press takes affect
		this.msOldTextBoxValue=this.GetTextBoxValue();
		
		var nKey;
		nKey=this.GetKey(evt);
				
		//Detect if the user is using the down button
		if(nKey==38) //Up arrow
		{
			this.MoveDown()
		}
		else if(nKey==40) //Down arrow
		{
			this.MoveUp()
		}
		else if(nKey==13) //Enter
		{
			if (this.IsVisibleClueDiv())
			{
			   
				this.HideDiv();
				
				evt.cancelBubble = true;
				
				if (evt.returnValue) evt.returnValue = false;
				if (evt.stopPropagation) evt.stopPropagation();
				
				this.mbCancelSubmit=true;	
						
     		}
     		else
     		{
     			this.mbCancelSubmit=false;
     		}
		}
		else
		{
			this.HideDiv();
		}
				
		return true;    
    }
    
    this.MoveDown = MoveDown ;
    function MoveDown()
    {
    
        var itemIndex;
		itemIndex=this.selItemIndex-1;
		TRACE("MoveDown:"+itemIndex);
		
		if(itemIndex!=0)
		{
			this.SelectItem(itemIndex)
		}        
    }  
   
    this.OnMouseClick=OnMouseClick;  
    function OnMouseClick(nMenuIndex)
    {
        TRACE("OnMouseClick:"+nMenuIndex);
        this.selItemIndex=nMenuIndex;
        this.SetTextBoxValue();
		this.HideDiv();          
    }
    
    this.OnMouseOver = OnMouseOver ;
    function OnMouseOver(nMenuIndex)
	{
	    TRACE("OnMouseOver:"+nMenuIndex);
	    this.SelectItem(nMenuIndex);	    		   		
	}
   
    
    this.MoveUp=MoveUp ;
    function MoveUp()
    {
        var itemIndex;
		itemIndex=this.selItemIndex+1;
		 TRACE("MoveUp:"+itemIndex);
		
		//Check if menu item exists
		if(this.GetItemDiv(itemIndex))
		{
			this.SelectItem(itemIndex)
		}    
    }
    
    this.GetItemDiv = GetItemDiv;
    function GetItemDiv(itemIndex)
    {  
        var sItemID=this.GetItemDivID(itemIndex);
		return document.getElementById(sItemID)  
		    
         
    }
    
    this.GetItemDivID = GetItemDivID;
    function GetItemDivID(itemIndex)
    {        
        return (this.textBoxID + "_mi_" + itemIndex);    
    }
    
    this.GetSelItemDiv = GetSelItemDiv ;
    function GetSelItemDiv()
	{
	    TRACE("GetSelItemDiv:"+selItemIndex);
		return this.GetItemDiv(this.selItemIndex);
	}
	
	this.SelectIFrameItem = SelectIFrameItem ;
	function  SelectIFrameItem()
	{
	    
	}
    
    this.SelectItem = SelectItem ;
    function SelectItem(itemIndex)
    { 
        var item=this.GetItemDiv(itemIndex)
        TRACE("SelectItem:"+item);
					
		if(item)
		{
			if (item!=this.selItemIndex)
			{
				this.UnSelectItem();
				
				this.selItemIndex=itemIndex;
				this.SetTextBoxValue();
						
				item.className=this.selItemCSSClass;
			}
		}     
    }
    
    //unhighlights a div
    this.UnSelectItem = UnSelectItem ;
	function UnSelectItem()
	{
	   
	    var item=this.GetSelItemDiv();
	    TRACE("UnSelectItem:"+item);
		if(item)
		{
			item.className=this.itemCSSClass;
		}		
	}
    

///private
    var mbCancelSubmit;
    var msOldTextBoxValue="";
    var mbHasFocus;
    
    var selItemIndex = 0;
    
    function GetInnerHtml(oItem) //private
	{
	    var sOut;
		if (oItem.innerText)
		{
			sOut=oItem.innerText;   // IE
		}
		else if (oItem.textContent)
		{
			sOut=oItem.textContent; // Mozilla
		}
		return (sOut);	    
	}
    
    this.GetKey = GetKey;    
    function GetKey(evt)
	{
		evt = (evt) ? evt : (window.event) ? event : null;
		if (evt)
		{
			var cCode = (evt.charCode) ? evt.charCode :
					((evt.keyCode) ? evt.keyCode :
					((evt.which) ? evt.which : 0));
			return cCode; 
		}
	}
	
	this.IsVisibleClueDiv = IsVisibleClueDiv ;
	function IsVisibleClueDiv()
	{
		if (this.GetClueBaseDiv().style.visibility == 'hidden')
		{
			return false;
		}
		else
		{
			return true;
		}
	}
    
    this.LessChar = LessChar ;
    // if is abc character and it's length less 2 ,do something 
    function LessChar(value)  //private 
    {  
    TRACE("mnStartSearchIndex:"+this.mnStartSearchIndex);
		/*
		if(value.length<2)
		{
			var reg=new RegExp("[A-Za-z]+","i")
			if(reg.exec(value))
			{
				if(this.language=="cn")
				{
					this.ShowDiv("<span style='font-size:12px;color:#ff6600;'>输入不能小于2个字符！</span>");
				}
				else 
				{
					this.ShowDiv("<span style='font-size:12px;color:#ff6600;'>Please input more than 2 charaters.</span>");					
				}
				return  true;
			}			
		}
		* */
		return false ;
    }   
    
    //move the div to the txtboxctrl...
    this.MoveDivIfAbsolutePos = MoveDivIfAbsolutePos;    
    function MoveDivIfAbsolutePos()
	{
		var txtCtrl = this.GetTextBoxCtrl();
		var divClue = this.GetClueBaseDiv();
		
		if(txtCtrl==null || divClue==null ) return ;
			
		TRACE("MoveDivIfAbsolutePos Moving absolute");
		
		//GetPos(txtCtrl, divClue)
		if (this.PosTop < 0 && this.PosLeft < 0)
		{
		    var pos = getAbsolutePos(txtCtrl);
		    this.PosLeft = pos.x;
		    this.PosTop = pos.y + txtCtrl.clientHeight;
		}
		
		//Move divclue right under text box
		divClue.style.left = this.PosLeft + 'px';
		divClue.style.top  = (this.PosTop + 2) + 'px';
	}

    //获得控件在页面上的绝对位置
    function getAbsolutePos(obj)
    {
        var pos = { x: 0, y: 0 };
        var offset_x = obj.clientLeft;
        var offset_y = obj.clientTop;
        
        function innerFunction()
        {
            while(obj && (obj.style.position != "relative"))
            {
               pos.x += obj.offsetLeft;
               pos.y += obj.offsetTop;
               pos.x += obj.clientLeft;
               pos.y += obj.clientTop;
               //如果需要计算滚动条
               if(obj.scrollLeft)
                 pos.x += obj.clientLeft;
               if(obj.scrollTop)
                 pos.y += obj.scrollTop;
                 
               obj=obj.offsetParent;
            }
        }
        
        innerFunction();
        pos.x -= offset_x;
        pos.y -= offset_y;
        
        return pos;
    }

    function getPosition(o){
	    var nLt=0;
	    var nTp=0;
	    var offsetParent = o;
	    while (offsetParent!=null && offsetParent!=document.body) {
			    nLt+=offsetParent.offsetLeft;
			    nTp+=offsetParent.offsetTop;
     
	    if(!IsNav()){
		    parseInt(offsetParent.currentStyle.borderLeftWidth)>0?nLt+=parseInt(offsetParent.currentStyle.borderLeftWidth):"";
		    parseInt(offsetParent.currentStyle.borderTopWidth)>0?nTp+=parseInt(offsetParent.currentStyle.borderTopWidth):"";
     
		    }
     
	    offsetParent=offsetParent.offsetParent;
	    //alert(offsetParent.tagName);
     }
     
      return {x:nLt, y:nTp};
    }
	
	function GetPos(inputObj, divObj)
	{
		
	    TRACE("GetPos:");	  
		//var pos = getPosition(inputObj);
		var pos = getAbsolutePos(inputObj);		
		
		if(IsIE())
		{
			divObj.style.left = (pos.x -1) + 'px';
			divObj.style.top = (pos.y + 20) + 'px';
		}
		else
		{
			divObj.style.left = pos.x + 'px';
			divObj.style.top = (pos.y + 20) + 'px';
		}
	
	}


	
	//Utility functions	(don't need this.)
	function IsIE()
	{
		return ( navigator.appName=="Microsoft Internet Explorer" ); 
	}
	

	function IsNav()
	{
		return ( navigator.appName=="Netscape" );
	}

    // Make a call back to our server side page and return the results from our query 
	// to a DIV tag sitting under the text box
	this.GetDataFromServer = GetDataFromServer ;
	function GetDataFromServer(sUrl)
	{		
		TRACE("GetDataFromServer: " + sUrl);
	
		var oXmlHttp = GetXmlHttp();
		oXmlHttp.open("GET", sUrl, true);
		
		var me = this;	//Use it to be able to access ShowMenuDiv and HideMenuDiv in the function()
		oXmlHttp.onreadystatechange = function()
		{		   
			if (oXmlHttp.readyState == 4) 
			{  
				if (oXmlHttp.responseText!="")
				{ 
				    TRACE(me.mbHasFocus);
					if (me.mbHasFocus)
					{ 
						me.ShowDiv(oXmlHttp.responseText);						
					}
				}				
				else
				{	
//					if(me.language=="cn")
//					{
//						me.ShowDiv("<span style='font-size:12px;color:#ff6600;'>找不到该城市，请检查！</span>");
//					}
//					else 
//					{
//						me.ShowDiv("<span style='font-size:12px;color:#ff6600;'>Can not find city.</span>");					
//					}
					me.HideDiv()
				}
			}
		}
		
		oXmlHttp.send(null)
	}
    
    //Create and return XmlHttp object
	function GetXmlHttp()
	{
		
		try {
			oXmlHttp  =  new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
			oXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			oXmlHttp = false;
		}
		}
		
	
		if (!oXmlHttp && typeof XMLHttpRequest != 'undefined') 
		{
			oXmlHttp = new XMLHttpRequest();
		}
		
		return oXmlHttp;
	}    
    
    function TRACE(sText)
	{
		var txtTrace = document.getElementById("txtASBTrace");
		if (txtTrace != null)
			txtTrace.value = txtTrace.value + sText + "\n";
	}    
}