
function AutoSuggestControl(oTextbox , 
                            oProvider ) {
    
  
    this.cur  = -1;
    this.count=-1;
    this.layer = null;
    this.node=null;

    this.provider  = oProvider;

    this.textbox = oTextbox;

    this.timeoutId  = null;

    this.userText = oTextbox.value;
    
    this.init();
    
}


AutoSuggestControl.prototype.autosuggest = function (maintext,chinese,english,phonic,
                                                     bTypeAhead ) {
    

    this.cur = -1;
    this.count = -1;
    
    //make sure there's at least one suggestion
    if (maintext.length > 0) {
        if (bTypeAhead) {
           this.typeAhead(maintext[0]);
        }
        this.showSuggestions(maintext,chinese,english,phonic);
    } else {
        this.hideSuggestions();
    }
};

AutoSuggestControl.prototype.createDropDown = function () {

    //create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    document.body.appendChild(this.layer);    
    

    var oThis = this;
    this.layer.onmousedown = 
    this.layer.onmouseup = 
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown") {
           oThis.FindText(oTarget);
           oThis.hideSuggestions();
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
            oThis.textbox.focus();
        }
    };
    
};


AutoSuggestControl.prototype.getLeft = function () /*:int*/ {
    var oNode = this.textbox;
    var iLeft = 0;
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    return iLeft;
};


AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};


AutoSuggestControl.prototype.goToSuggestion = function (iDiff /*:int*/) {
    var cSuggestionNodes = this.layer.childNodes;
    
    if (cSuggestionNodes.length > 0) {
        var oNode = null;
    
        if (iDiff > 0) {
            if (this.cur < cSuggestionNodes.length-1) {
                oNode = cSuggestionNodes[++this.cur];
            }        
        } else {
            if (this.cur > 0) {
                oNode = cSuggestionNodes[--this.cur];
            }    
        }
        
        if (oNode) {
            this.highlightSuggestion(oNode.firstChild);
            this.textbox.value = oNode.firstChild.firstChild.nodeValue;
            this.node =oNode.firstChild;
        }
    }
};


AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

    switch(oEvent.keyCode) {
        case 38: //up arrow
           this.goToSuggestion(-1);
            break;
        case 40: //down arrow 
            this.goToSuggestion(1);
            break;
        case 27: //esc
            this.textbox.value = this.userText;
            this.selectRange(this.userText.length, 0);
            this.hideSuggestions();
            oEvent.returnValue = false;
            if (oEvent.preventDefault) {
                oEvent.preventDefault();
            }
            break;
        case 13: //enter
            if(this.cur >-1){
             this.FindTextWithIndex(this.cur);
             this.cur=-1;
            }
            this.hideSuggestions();
             oEvent.returnValue = false;
            if (oEvent.preventDefault) {
                oEvent.preventDefault();
            }
            break;
    }

};


AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;
    var oThis = this;
    
    //get the currently entered text
    this.userText = this.textbox.value;
    
    clearTimeout(this.timeoutId);

    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        
        this.timeoutId = setTimeout( function () {
            oThis.provider.requestSuggestions(oThis, false);
        }, 250);
        
      } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
       this.timeoutId = setTimeout( function () {
             // oThis.provider.requestSuggestions(oThis, true);
           //no typeahead
           oThis.provider.requestSuggestions(oThis, false);
        }, 250);
    }
};


AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};


AutoSuggestControl.prototype.FindTextWithIndex = function (i) {

         this.textbox.value = this.layer.childNodes[i].firstChild.firstChild.nodeValue;
           var divList1 = document.getElementById("list1");
           var divList2 = document.getElementById("list2");
           var node1 = document.createElement("div");
           var node2 = document.createElement("div");
           node1.innerHTML=divList1.childNodes[i].innerHTML;
           node2.innerHTML=divList2.childNodes[i].innerHTML;
           node1.className = "listtop";
           node2.className = "listtop";
           divList1.insertBefore(node1, divList1.childNodes[0]);
           divList2.insertBefore(node2, divList2.childNodes[0]);
};


AutoSuggestControl.prototype.FindText = function (oSuggestionNode) {
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i].firstChild;
        if (oNode == oSuggestionNode) {
            this.textbox.value = oNode.firstChild.nodeValue;
           //document.getElementById("compose").value +=this.layer.childNodes[i].childNodes[1].firstChild.nodeValue;
           var divList1 = document.getElementById("list1");
           var divList2 = document.getElementById("list2");
           var node1 = document.createElement("div");
           var node2 = document.createElement("div");
           node1.innerHTML=divList1.childNodes[i].innerHTML;
           node2.innerHTML=divList2.childNodes[i].innerHTML;
           node1.className = "listtop";
           node2.className = "listtop";
           divList1.insertBefore(node1, divList1.childNodes[0]);
           divList2.insertBefore(node2, divList2.childNodes[0]);
         
        }
    }
};

AutoSuggestControl.prototype.highlightSuggestion= function (oSuggestionNode) {

    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i].firstChild;
        var oNode1 = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            //oNode1.className = "current"
            this.count=i;
            oNode1.className = "current";

        } else if (oNode1.className  == "current") {
            //oNode.className = "";
            oNode1.className = "";
        }
    }
};


AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    

        oThis.handleKeyUp(oEvent);
    };
    
    this.textbox.onkeydown = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }    
        oThis.handleKeyDown(oEvent);
    };
    
  
    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };
    
    //create the suggestions dropdown
    this.createDropDown();
};

AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iEnd /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iEnd - this.textbox.value.length);      
        oRange.select();
        
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iEnd);
    }     

    this.textbox.focus();      
}; 


AutoSuggestControl.prototype.showSuggestions = function (maintext,chinese,english,phonic2) {
    
    var oDiv = null;
    var oMainText = null;
    var oChinese = null;
    this.layer.innerHTML = "";  //clear contents of the layer
    
    for (var i=0; i < maintext.length; i++) {
        oMainText = document.createElement("label");
        oChinese = document.createElement("label");
        oChinese.className="chinese";
        oMainText.innerHTML=maintext[i];
        oMainText.title=phonic2[i]+" ; "+english[i];
        oChinese.innerHTML=chinese[i];
        oDiv = document.createElement("div");
        oDiv.appendChild(oMainText);
        oDiv.appendChild(oChinese);
        this.layer.appendChild(oDiv);
    }
    
    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    this.layer.style.visibility = "visible";
};

AutoSuggestControl.prototype.filllist = function (pinyin,zhuyin,chinese,simple,english) {
    var element =document.getElementById("list1");
    var element2 = document.getElementById("list2");

    while (element2.firstChild) {
        element2.removeChild(element2.firstChild);
    }
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }

    var oList1 = document.createDocumentFragment();
    var oList2 = document.createDocumentFragment();

    for (var i=0; i < pinyin.length; i++) {
        oDiv1 = document.createElement("div");
        oDiv2 = document.createElement("div");
        oDiv2Lin1 = document.createElement("div");
        oDiv2Lin1a = document.createElement("span");
        oDiv2Lin1b = document.createElement("span");
        oDiv2Lin2 = document.createElement("div");
        oDiv2Lin3 = document.createElement("div");

        if(i%2){
            oDiv1.className = "list2";
            oDiv2.className = "list2";
        }
        else{
            oDiv1.className = "list1";
            oDiv2.className = "list1";
        }
        oDiv1.appendChild(document.createTextNode(chinese[i]));
        
        oDiv2Lin1a.appendChild(document.createTextNode(simple[i]));
        oDiv2Lin1b.appendChild(document.createTextNode(pinyin[i]));
        oDiv2Lin1b.className="line1phonic";
        oDiv2Lin1.appendChild(oDiv2Lin1a);
        oDiv2Lin1.appendChild(oDiv2Lin1b);
       
oDiv2Lin2.appendChild(document.createTextNode(zhuyin[i]));
oDiv2Lin2.className="line2ncr";
        oDiv2Lin3.appendChild(document.createTextNode(english[i]));
        oDiv2Lin3.className="line3english";

        oDiv2.appendChild(oDiv2Lin1);
        oDiv2.appendChild(oDiv2Lin2);
        oDiv2.appendChild(oDiv2Lin3);
        oList1.appendChild(oDiv1);
        oList2.appendChild(oDiv2);
    }
    document.getElementById("list1").appendChild(oList1);
    document.getElementById("list2").appendChild(oList2);

};



AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};


function SuggestionProvider() {
    this.http = zXmlHttp.createRequest();
}


SuggestionProvider.prototype.requestSuggestions = function (oAutoSuggestControl ,
                                                            bTypeAhead ) {

    var oHttp = this.http;
                      
    if (oHttp.readyState != 0) {
        oHttp.abort();
    }                 
    
    //define the data
    var oData = { 
        text: oAutoSuggestControl.userText,
        limit: document.getElementById("limit").value
    };
    
    //open connection to server
    oHttp.open("post", "suggestcc2.php", true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            var aResult = JSON.parse(oHttp.responseText);
            oAutoSuggestControl.autosuggest(aResult['chinese_simpl'],aResult['chinese'],aResult['english'],aResult['pinyin'],bTypeAhead);
            oAutoSuggestControl.filllist(aResult['pinyin'], aResult['zhuyin'],aResult['chinese'], aResult['chinese_simpl'], aResult['english']);
            
        }    
    };

    oHttp.send(JSON.stringify(oData));

};
