/* 
 * 自动完成的下拉列表
 * author:熊星  2008-10-14
 * version:1.0.1
 * url: ajax请求的url
 * bindId: 绑定的文本框id
 * minLength: 最少输入多长的字符才发送请求
 * callback:回调函数
 */
var READY_STATE_COMPLETE=4;
function AutoComplateCombox(url,bindId,minLength,callback){
    if(!url) return;
    
    this.binder = document.getElementById(bindId);
    this.oldValue = this.binder.value;    // 保存老的值
    this.xmlHttp = null;
    this.url = url;
    this.length = minLength ? minLength : 1;
    this.selectedIndex = -1;    //  当前选择行
    this.rows = new Array();    //  下拉的数组
    this.isShow = false;        //  是否显示了下拉列表
    this.callBack = null;
    if(callback){      //选择后的回传方法
        this.callBack = function(params){callback(params);}
    }
    var _comboxTmp = this;
    /*有输入就发生请求*/
    this.binder.onkeyup=function(){
        _comboxTmp.sendRequest();
    }
    /*失去焦点就隐藏*/
    this.binder.onblur=function(){
        /*延迟0.5S隐藏，让鼠标可以引发tr的click事件*/
        window.setTimeout(_comboxTmp.hide, 300);
    }
    this.binder.onkeydown=function(evt){_comboxTmp.move(evt);}
    
    this.initHtml();
}
/*发送ajax请求*/
AutoComplateCombox.prototype.sendRequest=function(){
  var v = this.binder.value;
  if((v.length < this.length)){
      this.oldValue = v;
      this.hide();
      return;
  }
  
  if(v==this.oldValue)  return;
  this.oldValue = v;
  
  var urlTmp = this.url + v

 var _comboxTmp = this;
 $.ajax({
     type:"get",
     dataType:"jsonp",
     url : urlTmp,
     success : function(data){
         _comboxTmp.onReadyState(data);
     }
 });
   
  /*
  if (window.XMLHttpRequest){
      this.xmlHttp = new XMLHttpRequest();
  } else if (window.ActiveXObject){
      this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE
  }
  // 设置AJAX返回
  var _comboxTmp = this;
  this.xmlHttp.onreadystatechange = function(){
      _comboxTmp.onReadyState.call(_comboxTmp);
  }
  this.xmlHttp.open('GET',urlTmp,true);
  this.xmlHttp.send(null);
  */
}
var g_reg = /\["([^"]*)","([^"]*)","([^"]*)"\]/g;
var com_tmp = "<tr><td class='name'>{0}</td><td class='num'>{1}</td></tr>";
/*AJAX回传*/
AutoComplateCombox.prototype.onReadyState=function(d){
    //var ready = this.xmlHttp.readyState;
   // if (ready == READY_STATE_COMPLETE){
    //    if(this.xmlHttp.status == 200 || this.xmlHttp.status == 0){
            //this.show(this.xmlHttp.responseText);
            // 处理google结果
            
           // var d = this.xmlHttp.responseText;
           var list;
           for(var key in d){
               list =d[key];
           }
           if(!list){
                this.hide();
                return;
           }

           var liArray = new Array();
            liArray.push("<table  cellpadding='0' cellspacing='0' border='0'  class='search_com'>");
            for(var i=0;i<list.length;i++){
                liArray.push(com_tmp.format(list[i][0],list[i][1]));
            }
            liArray.push("</table>");
            if(liArray.length ==2)
                this.hide();
            else
                this.show(liArray.join(""));
      //  }
   // }
}

/*显示数据*/
AutoComplateCombox.prototype.show=function(data){
    dc = document.getElementById("divComplate");
    if(data.replace(" ","").length == 0){
        this.hide();
        return;
    }
    
    dc.innerHTML = data;
    this.initTable();
    // 取表格应该显示的位置
    var e = this.binder, x = e.offsetLeft, y = e.offsetTop + e.clientHeight;
    while(e=e.offsetParent){x += e.offsetLeft;y += e.offsetTop;}
    oDiv = document.getElementById("divComplate");
    
    oDiv.style.top = y + "px";
    oDiv.style.left = x + "px";
    oDiv.style.display="block";
    IfrRef = document.getElementById("frmComplateShim");
    IfrRef.style.width = oDiv.offsetWidth + "px";
    IfrRef.style.height = oDiv.offsetHeight + "px";
    IfrRef.style.top = oDiv.offsetTop + "px";
    IfrRef.style.left = oDiv.offsetLeft + "px";
    IfrRef.style.display = "block";

    this.isShow = true;
}
  
AutoComplateCombox.prototype.hide=function(){
   this.selectedIndex = -1;
   this.isShow = false;
   dc = document.getElementById("divComplate");
   dc.style.display="none";
   document.getElementById("frmComplateShim").style.display="none";
}
/*上下移动*/
AutoComplateCombox.prototype.move=function(evt){
  if(!this.isShow || this.rows.length == 0)  return;
  
  if(!evt) evt = window.event;
  var newIndex=null;
  if(evt.keyCode==38){    // 上移
      newIndex = this.selectedIndex - 1;
  }else if(evt.keyCode==40){  // 下移
      newIndex = this.selectedIndex + 1;
  }
  /*
  else if(evt.keyCode==13){
      // 回车发送tab按键
      evt.keyCode=9;
      //this.hide();
      //return false;
      return;
  }
  */
  if(newIndex==null) return;
  if(newIndex<0)    // 小于0，则显示的是最后一行
      newIndex = this.rows.length-1;
  else if(newIndex>=this.rows.length)    // 大于总数，返回第1条
      newIndex = 0;

  if(this.selectedIndex != -1)
    this.rows[this.selectedIndex].className = "";
 
  this.rows[newIndex].className = "selected";
  this.selectedIndex = newIndex;
  
  this.selectedChange();
}
/*选择项，向文本框赋值*/
AutoComplateCombox.prototype.selectedChange=function(){
    if(this.selectedIndex == -1)  return;
    tds = this.rows[this.selectedIndex].getElementsByTagName("TD");
    if(tds.length == 0) return;
    if(this.callBack != null){
        var params = new Array();
        for(var i=0;i<tds.length;i++){
            params[i] = tds[i].innerHTML;
        }
        this.callBack(params);
    }else{
        this.binder.value = tds[0].innerHTML;
    }
    this.oldValue = tds[0].innerHTML;
}
AutoComplateCombox.prototype.clickSelect=function(row){
    tds = row.getElementsByTagName("TD");
    if(tds.length == 0) return;
    if(this.callBack != null){
        var params = new Array();
        for(var i=0;i<tds.length;i++){
            params[i] = tds[i].innerHTML;
        }
        this.callBack(params);
    }else{
        this.binder.value = tds[0].innerHTML;
    }
    this.oldValue = tds[0].innerHTML;
    this.hide();
}
/*初始化html*/
AutoComplateCombox.prototype.initHtml=function(){
    /*
    var style="<style type='text/css'>\r\n" +
          "#divComplate{width:400px; background-color:#fff;font-size:9pt;display:none;position:absolute;z-index:900;border-top:1px solid #EEEEED;border-left:1px solid #EEEEED;border-right:1px solid #ccc;border-bottom:1px solid #ccc;}\r\n" +
          "#divComplate table{font-size:9pt;}\r\n" +
          "#divComplate table th{background-color:#F4F4F4;font-weight:normal;padding:5px;}\r\n"+
          "#divComplate table td{padding:2px 4px;}\r\n" +
          "#divComplate table tr.selected td{background-color:#F2F5FC;}\r\n</style>";
    */
    var html = "<iframe id='frmComplateShim' src='' style='background-color:#fff;position:absolute;z-index:890;display:none;' scrolling='no' frameborder='0'></iframe><div id='divComplate'></div>";
   // document.write(style);
    document.write(html);
}
/*初始化表格*/
AutoComplateCombox.prototype.initTable=function(){
    trs = document.getElementById("divComplate").getElementsByTagName("tr");
    this.clearRows();
    this.selectedIndex = -1;
    var tmp = this;
    for(var i=0;i<trs.length;i++){
        if(trs[i].className!="auto_head"){
            trs[i].onmouseover = function(){this.className="selected";}
            trs[i].onmouseout = function(){this.className="";}
            trs[i].onclick = function(){tmp.clickSelect(this);}
            this.rows.push(trs[i]);
        }
    }
}
/*清空数据*/
AutoComplateCombox.prototype.clearRows=function(){
    if(this.rows.length > 0){
        count = this.rows.length-1;
        for(var i=count;i>=0;i--){
            this.rows.pop();
        }
    }
}
