
TextAutoCompleteObj = Class.create();

TextAutoCompleteObj.prototype = {
		/**
     * anId:要实现自动提示的文本框ID
     * url:服务地址
     * options:选项
     */
   initialize: function( service ,anId, options) {
      this.id          = anId;
      var browser = navigator.userAgent.toLowerCase();
      this.isIE        = browser.indexOf("msie") != -1;
      this.isOpera     = browser.indexOf("opera")!= -1;
      this.textInput   = $(this.id);
      this.suggestions = [];
      this.setOptions(options);
      this.service     = service;
      //初始化Suggest
      this.injectSuggestBehavior();
   } ,
   //设置可选项
   setOptions: function(otherOptions) {
      this.options = {
         suggestSpanClassName: 'spanTextDropdown',
         suggestOptionClassName: 'suggestion',
         suggestSpanSuffix: '_spanOutput',
         matchClassName     : 'match',
         matchTextWidth     : true,
         selectionColor     : '#b1c09c',
         matchAnywhere      : false,
         ignoreCase         : false,
         count              : 10,
         maxRecord          : 10,
         searchTableName    : 'searchTableName',
         searchFldName      : 'searchFldName',
         searchValue        : 'searchValue',
         returnFldNames     : 'returnFldNames',
         writeFldNames      : 'writeFldNames',
         condition          : 'condition',
         orgCodeFilter      : 'orgCodeFilter'
      };
    if (otherOptions){
      if (otherOptions.searchTableName){
      	this.options.searchTableName = otherOptions.searchTableName;
      }
      if (otherOptions.searchFldName){
      	this.options.searchFldName = otherOptions.searchFldName;
      }
      if (otherOptions.searchValue){
      	this.options.searchValue = otherOptions.searchValue;
      }
      if (otherOptions.returnFldNames){
      	this.options.returnFldNames = otherOptions.returnFldNames;
      }
      if (otherOptions.writeFldNames){
      	this.options.writeFldNames = otherOptions.writeFldNames;
      }
      if (otherOptions.condition){
      	this.options.condition = otherOptions.condition;
      }
      if (otherOptions.orgCodeFilter){
      	this.options.orgCodeFilter = otherOptions.orgCodeFilter;
      }
    }
      
   },
   //返回SuggestSpan的ID
   getSuggestSpanId: function(){
   	return this.id+this.options.suggestSpanSuffix;
   },
   injectSuggestBehavior : function(){
   	//生成SuggestSpan
		var suggestSpan = document.createElement("span");
		suggestSpan.id = this.getSuggestSpanId();
		suggestSpan.className = this.options.suggestSpanClassName;
		suggestSpan.curOptionIndex = -1;
		suggestSpan.optionNum = -1;
		//将新生成的span加入到页面中
    	document.body.appendChild(suggestSpan);
    	this.suggestSpan = suggestSpan;
    	//设置suggestSpan的位置
    	this.setSuggestSpanPosition();
    	//注册键盘响应事件
    	Event.observe(this.textInput, 'keyup', this.keyUpHandle.bindAsEventListener(this), true);
    	Event.observe(this.textInput, 'keydown', this.breakEvent.bindAsEventListener(this), true);
    	

   },
   breakEvent : function(e){
   	var intKey = -1;
	if(window.event){
		intKey = event.keyCode;
	}else{
		intKey = e.which;
	}
	if (intKey == 13){
		var outputSpan = this.suggestSpan;
		if (outputSpan.style.display == "block" ){
			Event.stop(e);
		}
	}
	
	
		
   },
   displaySpan : function(){
   		if (this.suggestSpan.datas && this.suggestSpan.datas.length > 0){
   			this.suggestSpan.style.display = "block";
			//clearTimeout(this.timeoutId);
			//setTimeout(this.hideSpan.bindAsEventListener(this),5000);
   		}
		
   },
   hideSpan : function(){
		this.suggestSpan.style.display = "none";
		clearTimeout(this.timeoutId);
   },
   //键盘响应事件
   keyUpHandle : function(e){
   		clearTimeout(this.timeoutId);
		var theTextBox = this.textInput;
		var intKey = -1;
		if(window.event){
			intKey = event.keyCode;
		}else{
			intKey = e.which;
		}
		
		
		
    	var outputSpan = this.suggestSpan;
		var curOptionIndex = outputSpan.curOptionIndex;

		//回车
		if(intKey == 13){
			if (outputSpan.style.display == "none" || outputSpan.style.display == ""){
				this.request();
				
			}else{
				//得到当前选项
				var curOption = document.getElementById(this.id+'_OptionsList_' + curOptionIndex);
				this.setText(curOption);
				this.hideSpan();
				//Event.stop(e);
			}
			
		}else if(intKey == 38){//上
		
			if (outputSpan.style.display == "none"  || outputSpan.style.display=="" ){
				this.displaySpan();
			}
			if (this.suggestSpan.datas && this.suggestSpan.datas.length > 0){
   				curOptionIndex--;
				if (curOptionIndex < 0){
					curOptionIndex = outputSpan.optionNum-1;
				}
				//得到当前option
				var curOption = document.getElementById(this.id+'_OptionsList_' + curOptionIndex)
				this.SetHighColor(curOption);
				return false;
   			}
			
		}else if(intKey == 40){//上
		
			if (outputSpan.style.display == "none"  || outputSpan.style.display=="" ){
				this.displaySpan();
			}
			if (this.suggestSpan.datas && this.suggestSpan.datas.length > 0){
   				curOptionIndex = (parseInt(curOptionIndex)+1);
				if (curOptionIndex > outputSpan.optionNum-1){
					curOptionIndex = 0;
				}
				//得到当前option
				var curOption = document.getElementById(this.id+'_OptionsList_' + curOptionIndex)
				this.SetHighColor(curOption);
				return false;
   			}
   			
			
		}else{
			if (intKey != 9){
				this.request();
			}
			
		}
   },
   request : function(){
   		var previousRequest    = this.lastRequestString;
     	this.lastRequestString = this.textInput.value;
     	if ( this.lastRequestString == "" )
        	this.hideSpan();
     	else if ( this.lastRequestString != previousRequest && !this.handlingRequest) {
     		
     		
     	
     		var param = this.options.searchValue+"="+encodeURIComponent(this.textInput.value.trim());
     		param += "&"+this.options.searchTableName+"="+encodeURIComponent(this.textInput[this.options.searchTableName].trim());
   			param += "&"+this.options.searchFldName+"="+encodeURIComponent(this.textInput[this.options.searchFldName].trim());
   			param += "&"+this.options.returnFldNames+"="+encodeURIComponent(this.textInput[this.options.returnFldNames].trim());
   			param += "&"+this.options.writeFldNames+"="+encodeURIComponent(this.textInput[this.options.writeFldNames].trim());
     		if (this.textInput.condition){
   				param += "&"+this.options.condition+"="+encodeURIComponent(this.textInput[this.options.condition]);
   			}
   			if (this.textInput.orgCodeFilter){
   				param += "&"+this.options.orgCodeFilter+"="+encodeURIComponent(this.textInput[this.options.orgCodeFilter].trim());
   			}
     		
   			
   			new Ajax.Request(this.service,{method:'post',parameters:param,onComplete:this.completeCallback.bindAsEventListener(this)});		
        	
     		this.handlingRequest = true;
     	}
     	
   },
   completeCallback : function(obj){
   		//alert(obj.responseText);
   		var rtnObj = eval("rtnObj = "+obj.responseText);
   		//alert(rtnObj);
   		var datas = rtnObj.map.result.list;
   		this.buildOptionSpan(datas);
   		this.suggestSpan.datas = datas;
   		
   		this.handlingRequest = false;
   		if (datas != null && datas != 'undefined' && datas.length > 0){
   			this.displaySpan();
   		}
   },
   buildOptionSpan : function(datas){
   		this.clearSpan();
   		if (!datas){
   			return;
   		}
   		
   		//如果searchFldName有多个的话,取第一个searchFldName
   		var searchFldName = this.textInput[this.options.searchFldName];
   		//alert(searchFldName);
   		var searchFldNameArray = searchFldName.split(',');
   		
   		if (searchFldNameArray){
   			searchFldName = searchFldNameArray[0];
   		}
   		
   		for (var i = 0 ; i < datas.length ; i++){
   			var spanObj = document.createElement('span')
				spanObj.className="spanNormalElement";
				spanObj.id=this.id+"_OptionsList_"+i;
				Event.observe(spanObj, 'mouseover', this.mouseoverHandle.bindAsEventListener(this), false);
				Event.observe(spanObj, 'click', this.clickHandle.bindAsEventListener(this), false);
				//onmouseover="SetHighColor(this)";
				spanObj.value=datas[i].map[searchFldName];
				spanObj.theArrayNumber=i;
				spanObj.style.width='100%';
				var textNode = document.createTextNode(datas[i].map[searchFldName]);
				spanObj.appendChild(textNode);
				this.suggestSpan.appendChild(spanObj);
   		}
   		if (datas.length > 0){
   			this.suggestSpan.curOptionIndex = 0;
   			this.suggestSpan.optionNum = datas.length;
   			this.SetHighColor($(this.id+"_OptionsList_0")); 
   		}
   		
   		
   },
   clickHandle : function(e){
   	var curOption;
   	if(window.event){
			curOption = event.srcElement;
		}else{
			curOption = e.target;
		}
   	this.setText(curOption);
   },
   setText : function(curOption){
   		var datas = this.suggestSpan.datas;
   		if (datas == null || datas.length <= 0){
   			return ;
   		}
   		var theOptionParent = curOption.offsetParent;
		var theTextBox = this.textInput;
		curOption.offsetParent.style.display = "none";
		
		
		//得到returnFldNames
		var returnFldNames = this.textInput[this.options.returnFldNames];//07.09.1修改
		if (returnFldNames == null || returnFldNames == "" ){
			return ;
		}
		//得到writeFldNames
		var writeFldNames = this.textInput[this.options.writeFldNames];//07.09.1修改
		if (writeFldNames == null || writeFldNames == "" ){
			return ;
		}
		try{
			var returnFldNamesArray = returnFldNames.split(',');
			var writeFldNamesArray = writeFldNames.split(',');
			if (returnFldNamesArray != null && 
		    	writeFldNamesArray != null &&
		    	returnFldNamesArray.length == writeFldNamesArray.length
			){
				var index = curOption.theArrayNumber;
				var data = datas[index];
				
				for (var i = 0 ; i < returnFldNamesArray.length ; i++){
					$(writeFldNamesArray[i]).value=data.map[returnFldNamesArray[i]];
				}
			}
			
			//得到returnBtn
			var returnBtn = this.textInput[this.options.returnBtn];//07.09.1修改
			if (returnBtn){
				$(returnBtn).click();
			}
		}catch(e){
			
		}
		
		theTextBox.value = curOption.value; 
   },
   mouseoverHandle : function(e){
   	var curOption;
   	if(window.event){
			curOption = event.srcElement;
		}else{
			curOption = e.target;
		}
   	this.SetHighColor(curOption);   
   },
   SetHighColor : function(curOption){
   			var curOptionId = this.id+"_OptionsList_"+this.suggestSpan.curOptionIndex;
      	var theOption = curOption;
      	var theOptionParent = this.suggestSpan;	
        var optionNum = theOptionParent.optionNum;
        for(i = 0; i < optionNum; i++){
          document.getElementById(this.id+'_OptionsList_' + i).className =
            'spanNormalElement';
        }
        theOption.className='spanHighElement';
        this.suggestSpan.curOptionIndex = theOption.theArrayNumber;     
   },
   clearSpan : function(datas){
   		this.suggestSpan.innerHTML = "";
   },
   setSuggestSpanPosition:function(){
   		setDivPosition(this.id,this.suggestSpan);
   		/*
        var selectedPosX = 0;
        var selectedPosY = 0;
        var theElement = this.textInput;
        if (!theElement) return;	
        var theElemHeight = theElement.offsetHeight;
        var theElemWidth = theElement.offsetWidth;
        while(theElement != null){
          selectedPosX += theElement.offsetLeft;
          selectedPosY += theElement.offsetTop;
          theElement = theElement.offsetParent;
        }
        xPosElement = this.suggestSpan;
        xPosElement.style.left = selectedPosX;
        xPosElement.style.width = theElemWidth;
        xPosElement.style.top = selectedPosY + theElemHeight;
     */
	}
}


function setDivPosition(inputName,completeDiv){
	
  	var inputObj = $(inputName);
	
	var pos = getPos(inputObj);
	
  	completeDiv.style.left=pos[1]+'px';
	
  	completeDiv.style.border='black 1px solid';
  	
	completeDiv.style.top=pos[0]+inputObj.offsetHeight+'px';
  	completeDiv.style.width=inputObj.offsetWidth+'px';		
}

function   getPos(obj)   
  {   
          
		  var   pos   =   new   Array();   
          var   t=obj.offsetTop;   
          var   l=obj.offsetLeft;   
          while(obj=obj.offsetParent)   
          {   
                  t+=obj.offsetTop;   
                  l+=obj.offsetLeft;   
          }   
          pos[0]   =   t;   
          pos[1]   =   l;   
          return   pos;   
  }  




