
function AutoSuggestControl(oTextbox, 
                            oProvider ) {
    
    this.cur = -1;
    this.count=-1;
    this.layer = null;
    this.provider = oProvider;
    this.textbox  = oTextbox;
    this.timeoutId  = null;
    this.userText  = oTextbox.value;
    this.init();
}


AutoSuggestControl.prototype.autosuggest = function (phonic,chinese,english,bTypeAhead ) {
    
    this.cur = -1;
    this.count = -1;
    
    if (phonic.length > 0) {
        if (bTypeAhead) {
           this.typeAhead(phonic[0]);
        }
        this.showSuggestions(phonic,chinese,english);
    } 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 () {
    var oNode = this.textbox;
    var iLeft = 0;
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    return iLeft;
};

AutoSuggestControl.prototype.getTop = function () {

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

AutoSuggestControl.prototype.goToSuggestion = function (iDiff ) {
    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;
        }
    }
};


AutoSuggestControl.prototype.handleKeyDown = function (oEvent ) {

    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);
            /* falls through */
        case 13: //enter
        
            if(this.cur > -1){
                this.ShowNodebyIndex(this.cur);
                this.cur =-1;
            }
            this.hideSuggestions();
            oEvent.returnValue = false;
            if (oEvent.preventDefault) {
                oEvent.preventDefault();
            }
            break;
    }

};

AutoSuggestControl.prototype.handleKeyUp = function (oEvent ) {

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

    if (iKeyCode == 8 || iKeyCode == 46) {
        
        this.timeoutId = setTimeout( function () {
            oThis.provider.requestSuggestions(oThis, false);
        }, 250);
        
    //make sure not to interfere with non-character keys
    } 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.ShowNodebyIndex = 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;
           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) {
            this.count=i;
            oNode1.className = "current";
        } else if (oNode1.className  == "current") {
            oNode1.className = "";
        }
    }
};


AutoSuggestControl.prototype.init = function () {

    var oThis = this;
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {

        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();
    };
    
    this.createDropDown();
};


AutoSuggestControl.prototype.selectRange = function (iStart , iEnd ) {

    //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();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iEnd);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

AutoSuggestControl.prototype.showSuggestions = function (phonic,chinese,english) {
    
    var oDiv = null;
    var oPhonic = null;
    var oChinese = null;
    this.layer.innerHTML = "";  
    
    for (var i=0; i < phonic.length; i++) {
        oPhonic = document.createElement("label");
        oChinese = document.createElement("label");
        oChinese.className="chinese";
        //oPhonic.className="phonic";
        oPhonic.innerHTML=phonic[i];
        oPhonic.title=english[i];
        oChinese.innerHTML=chinese[i];
        oDiv = document.createElement("div");
        oDiv.appendChild(oPhonic);
        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,phonic,ncr,chinese,english,zhuyin) {
    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");
        oDiv1Line1 = document.createElement("div");
        oDiv1Line2 = 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";
        }
        oDiv1Line1.appendChild(document.createTextNode(pinyin[i]));
        //oDiv1Line2.appendChild(document.createTextNode(phonic[i]));
        //oDiv1Line2.className="line1phonic";
        oDiv1.appendChild(oDiv1Line1);
        //oDiv1.appendChild(oDiv1Line2);
        
        oDiv2Lin1a.appendChild(document.createTextNode(chinese[i]));
        oDiv2Lin1b.appendChild(document.createTextNode(phonic[i]));
        oDiv2Lin1b.className="line1phonic";
        oDiv2Lin1.appendChild(oDiv2Lin1a);
       oDiv2Lin1.appendChild(oDiv2Lin1b);
       
        //oDiv2Lin2.appendChild(document.createTextNode(ncr[i]));
        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 ) {

    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 languagetype="trad";
    var form1 =document.getElementById("search");
    for (var i = 0; i < form1.language.length; i++) {
        if (form1.language[i].checked) {
            languagetype = form1.language[i].value;
            break;
        }
    }
    
    var oHttp = this.http;
                      
    if (oHttp.readyState != 0) {
        oHttp.abort();
    }                 
    
    var oData = { 
        language: languagetype,
        text: oAutoSuggestControl.userText,
        limit: document.getElementById("limit").value
    };

    oHttp.open("post", "suggestpinyin.php", true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            var aResult = JSON.parse(oHttp.responseText);
            oAutoSuggestControl.autosuggest(aResult['pinyin'],aResult['chinese'],aResult['english'], bTypeAhead);
            oAutoSuggestControl.filllist(aResult['pinyin'], aResult['phonic'],aResult['chinese_ncr'], aResult['chinese'], aResult['english'],aResult['zhuyin']);
        }    
    };
    oHttp.send(JSON.stringify(oData));
};
