
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.selectRange(this.userText.length, 0);
            this.cur =-1;
            this.hideSuggestions();
            oEvent.returnValue = false;
            if (oEvent.preventDefault) {
                oEvent.preventDefault();
            }
            break;

        case 13: //enter
        
            if(this.cur > -1){
                this.ShowNodebyIndex(this.cur);
                this.cur =-1;
            }
            else if(this.layer.childNodes[0].firstChild.firstChild != null && this.textbox.value !=""){
              this.ShowNodebyIndex(0);
              this.cur =-1;
              this.textbox.value = "";
            }
            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");
           var pinyin_num="";
           var strpinyin="";
           var pinyin_num =divList1.childNodes[i].childNodes[0].innerHTML;
           node1.innerHTML=this.getAudioFlashCode(pinyin_num);
           node2.innerHTML=divList2.childNodes[i].innerHTML;
           document.getElementById("history").innerHTML = document.getElementById("history").innerHTML+divList2.childNodes[i].childNodes[0].childNodes[0].innerHTML;
       
           node1.className = "listtop";
           node2.className = "listtop";
           divList1.insertBefore(node1, divList1.childNodes[0]);
           divList2.insertBefore(node2, divList2.childNodes[0]);
           window.scroll(0,0);
           this.textbox.value = "";
           
};
AutoSuggestControl.prototype.FindText = function (oSuggestionNode) {
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i].firstChild;
        var oNode_last = this.layer.childNodes[i].lastChild;
        if (oNode == oSuggestionNode || oNode_last == 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");
           document.getElementById("history").innerHTML = document.getElementById("history").innerHTML+divList2.childNodes[i].childNodes[0].childNodes[0].innerHTML;
           
           var pinyin_num =divList1.childNodes[i].childNodes[0].innerHTML;
           node1.innerHTML=this.getAudioFlashCode(pinyin_num);
           node2.innerHTML=divList2.childNodes[i].innerHTML;
           
           node1.className = "listtop";
           node2.className = "listtop";
           divList1.insertBefore(node1, divList1.childNodes[0]);
           divList2.insertBefore(node2, divList2.childNodes[0]);
            window.scroll(0,0);
            this.textbox.value = "";
           // document.getElementById("history").value+=divList2.childNodes[i].firstchild.innerHTML;
           
        }
    }
};

AutoSuggestControl.prototype.getAudioFlashCode = function (pinyin_num) {
 
           var strpinyin="";
           pinyin_num=pinyin_num.replace(":","-");
           pinyin_num=pinyin_num.replace("   "," ");
           pinyin_num=pinyin_num.replace("  "," ");

            var pinyin_array = pinyin_num.split(" ");

           for(var k=0; k<pinyin_array.length; k++ ){
              if( k==pinyin_array.length-1){
                strpinyin+="http%3A%2F%2Fwww.cozychinese.com%2Faudio%2F"+pinyin_array[k]+".mp3"
                //alert(strpinyin);
              }else{
              strpinyin+="http%3A%2F%2Fwww.cozychinese.com%2Faudio%2F"+pinyin_array[k]+".mp3%2c";
              }
           }

var strAudio="<object type=\"application/x-shockwave-flash\" data=\"http://www.cozychinese.com/wp-content/plugins/audio-player/player.swf\" id=\"audioplayer1\" height=\"20\" width=\"200\"><param name=\"movie\" value=\"http://www.cozychinese.com/wp-content/plugins/audio-player/player.swf\"><param name=\"FlashVars\" value=\"playerID=1&amp;bg=0xf8f8f8&amp;leftbg=0xeeeeee&amp;lefticon=0x666666&amp;rightbg=0xcccccc&amp;rightbghover=0x999999&amp;righticon=0x666666&amp;righticonhover=0xCCFF66&amp;text=0x666666&amp;slider=0x666666&amp;track=0xFFFFFF&amp;border=0x666666&amp;loader=0x9FFFB8&amp;soundFile="+strpinyin+"\"><param name=\"quality\" value=\"high\"><param name=\"menu\" value=\"false\"><param name=\"wmode\" value=\"transparent\"><param name=\"bgcolor\" value=\"#FFFFFF\" /></object>";
//alert(strAudio);
return strAudio;

}

AutoSuggestControl.prototype.highlightSuggestion= function (oSuggestionNode) {

    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i].firstChild;
        var oNode_last = this.layer.childNodes[i].lastChild;
        var oNode1 = this.layer.childNodes[i];
        if (oNode == oSuggestionNode || oNode_last == 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.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,pinyin_num) {
    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");
       // oDiv2Lin1c = 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_num[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]));
        //oDiv2Lin1c.appendChild(document.createTextNode("   "+pinyin_num[i]));
        oDiv2Lin1b.className="line1phonic";
        oDiv2Lin1a.className="line1chinese";
        oDiv2Lin1.appendChild(oDiv2Lin1a);
       oDiv2Lin1.appendChild(oDiv2Lin1b);
       // oDiv2Lin1.appendChild(oDiv2Lin1c);
       
        //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 oHttp = this.http;
                      
    if (oHttp.readyState != 0) {
        oHttp.abort();
    }                 
    
    var oData = { 
        language: document.getElementById("lang").value,
        text: oAutoSuggestControl.userText,
        limit: document.getElementById("limit").value
    };

    oHttp.open("post", "/include/pinyin_type.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'],aResult['pinyin_num']);
        }    
    };
    oHttp.send(JSON.stringify(oData));
};
