function cleartext(){
  if(document.getElementById("mytext").value ==="Text Area**"){
        document.getElementById("mytext").value="";
    }
}
function cleartextfield(){
  document.getElementById("PinYin").value ="";
}

function AddtoText(textin){
  cleartext();
  if(textin!=""){
    document.getElementById("mytext").value+=textin;
  }
}
    
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;
    document.getElementById("mytext").value = "Text Area**";
    document.getElementById("convert").style.display="none";
    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 () {

    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 /*: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;
        }
    }
};

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

    switch(oEvent.keyCode) {
        case 38: 
            this.goToSuggestion(-1);
            break;
        case 40: 
            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.AddtoTextBox(this.cur);
                //this.cur =-1;
            }
            else if(this.layer.childNodes[0]!=null){
              if(this.textbox.value ==this.layer.childNodes[0].firstChild.firstChild.nodeValue)
                {this.AddtoTextBox(0);}
            }

            this.hideSuggestions();
           oEvent.returnValue = false;
            if(oEvent.preventDefault){
                oEvent.preventDefault();
                oEvent.stopPropagation();
            }
            break;
    }

};

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

    var iKeyCode = oEvent.keyCode;
    var oThis = this;
    this.userText = this.textbox.value;
    clearTimeout(this.timeoutId);
    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)) {
    } 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.AddtoTextBox = function (i) {
    this.textbox.value = this.layer.childNodes[i].firstChild.firstChild.nodeValue;
     var selectedText=this.layer.childNodes[i].childNodes[1].firstChild.nodeValue;
     document.getElementById("mytext").value +=selectedText;
};



AutoSuggestControl.prototype.FindText = function (oSuggestionNode) {
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode  = this.layer.childNodes[i].firstChild;
        var oNode2 = this.layer.childNodes[i].childNodes[1];
        if (oNode == oSuggestionNode || oNode2 == oSuggestionNode) {
            this.AddtoTextBox(i);
        }
    }
};

AutoSuggestControl.prototype.highlightSuggestion= function (oSuggestionNode) {

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

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

AutoSuggestControl.prototype.init = function () {

    var oThis = this;
    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 /*: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();
        
    //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 = "";  //clear contents of the layer
    
    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=chinese[i]+"; "+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.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    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;
    var inputoption="pinyin";
    var languagetype="trad";
    var form1 =document.getElementById("search1");

    cleartext();
                                   
    //cancel any active requests                          
    if (oHttp.readyState != 0) {
        oHttp.abort();
    }
    for (var i = 0; i < form1.inputtype.length; i++) {
        if (form1.inputtype[i].checked) {
            inputoption = form1.inputtype[i].value;
            break;
        }
    }
    for (var i = 0; i < form1.language.length; i++) {
        if (form1.language[i].checked) {
            languagetype = form1.language[i].value;
            break;
        }
    }
    
    //define the data
    var oData = { 
        inputtype:inputoption,
        language:languagetype,
        text: oAutoSuggestControl.userText,
        limit: document.getElementById("limit").value
    };
    
    //open connection to server
    oHttp.open("post", "suggestpinyin.php", true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            //evaluate the returned text JavaScript (an array)
            var aResult = JSON.parse(oHttp.responseText);
            //provide suggestions to the control
          if(inputoption =="pinyin"){
            oAutoSuggestControl.autosuggest(aResult['pinyin'],aResult['chinese'],aResult['english'], bTypeAhead);
          }
          else{
            oAutoSuggestControl.autosuggest(aResult['english'],aResult['chinese'],aResult['phonic'], bTypeAhead);
          }
            
        }    
    };

    //send the request
    oHttp.send(JSON.stringify(oData));

};

function convert(sOutputType) {
    var oHttp = zXmlHttp.createRequest();
    document.getElementById("convertedtext").value="converting...";
     document.getElementById("convert").style.display="block";
     var mytext=document.getElementById("mytext").value;
     if(sOutputType=="unicode"){}
     else{mytext= escape(mytext);     }
    var oData = {
        outputtype: sOutputType,
        text: mytext
    };

    //open connection to server
    oHttp.open("post", "convertunicode.php", true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            var aResult = JSON.parse(oHttp.responseText);
            document.getElementById("convertedtext").value =unescape(aResult);
        }
    };
    oHttp.send(JSON.stringify(oData));
};

function translate(sOutputType) {
    var oHttp = zXmlHttp.createRequest();
    document.getElementById("convertedtext").value="converting...";
     document.getElementById("convert").style.display="block";
    //define the data
    var oData = {
        outputtype: sOutputType,
        text: escape(document.getElementById("mytext").value)
    };

    oHttp.open("post", "translate.php", true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            //evaluate the returned text JavaScript (an array)
            var aResult = JSON.parse(oHttp.responseText);
            document.getElementById("convertedtext").value =unescape(aResult);
        }
    };
    oHttp.send(JSON.stringify(oData));
};
