var tempAutoSuggest;
var tid;

function lookupWord(str)
{
	var newUrl = window.location.protocol + '//' + window.location.host + '/?word=' + str;
	window.location = newUrl;
	
	/*
    lastLookupWord = str;
    if (str.length == 0)
    {
        return false;
    }
    
    if (!(str=="map" || str=="eval" || str=="every"))
    {
        if (lookupArray[str] != null)
        {
            document.getElementById("meaning_div").innerHTML = lookupArray[str];
            return false;
        }
    }
    
    xmlHttp = getXmlHttpObject();
    if(xmlHttp == null)
    {
        alert("Browser doesn't support HTTP request.");
        return;
    }
    
    var url = "dictionary_lookup.php?word=" + str;
    
    xmlHttp.onreadystatechange = wordLookupStateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    
    return false;
	*/
}

function lookupById(w_id)
{
    document.lookup_form.word.value = '';
    lastLookupWord = w_id;
    if (w_id <= 0)
    {
        return false;
    }
    
    if (lookupArray[w_id] != null)
    {
        document.getElementById("meaning_div").innerHTML = lookupArray[w_id];
        return false;
    }
    
    xmlHttp = getXmlHttpObject();
    if(xmlHttp == null)
    {
        alert("Browser doesn't support HTTP request.");
        return;
    }
    
    var url = "dictionary_lookup.php?wordID=" + w_id;
    
    xmlHttp.onreadystatechange = wordLookupStateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    
    return false;
}

function wordLookupStateChanged()
{
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
    {
        document.getElementById("meaning_div").innerHTML = xmlHttp.responseText;
        lookupArray[lastLookupWord] = xmlHttp.responseText;
    }
    else if (xmlHttp.readyState == 1)
    {
        document.getElementById("meaning_div").innerHTML = "<center><br>Looking up word in dictionary...<br><br><img src='images/book_flip.gif'><br><br></center>";
    }
}

function getXmlHttpObject(handler)
{
    var objXMLHttp = null;
    if (window.XMLHttpRequest)
    {
        objXMLHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    return objXMLHttp;
}

function trimWord(inputText)
{
    if(inputText.length>0) 
	{
		var i = 0;
		var temp = "";
		for(i=0; i<inputText.length; i++)
		{
			if (inputText.charCodeAt(i) == 304)
			{
				// we have an i
				inputText = inputText.substring(0, i) + 'i' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 350)
			{
				// we have a S
				inputText = inputText.substring(0, i) + 's' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 286)
			{
				// we have a G
				inputText = inputText.substring(0, i) + 'g' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 287)
			{
				// we have a G
				inputText = inputText.substring(0, i) + 'g' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 351)
			{
				// we have a S
				inputText = inputText.substring(0, i) + 's' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 305)
			{
				// we have an I
				inputText = inputText.substring(0, i) + 'i' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 252)
			{
				// we have an ü
				inputText = inputText.substring(0, i) + 'u' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 220)
			{
				// we have an Ü
				inputText = inputText.substring(0, i) + 'u' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 231)
			{
				// we have a ç
				inputText = inputText.substring(0, i) + 'c' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 199)
			{
				// we have a Ç
				inputText = inputText.substring(0, i) + 'c' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 246)
			{
				// we have an ö
				inputText = inputText.substring(0, i) + 'o' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 214)
			{
				// we have an Ö
				inputText = inputText.substring(0, i) + 'o' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 39)
			{
				// we have an Ö
				inputText = inputText.substring(0, i) + '' + inputText.substring(i+1, inputText.length);
			}
		}
		
		return inputText;
	} else
	{
		return "";
	}
}

function makeStringViewable(inputText)
{
    if (inputText.length>0)
    {
        inputText = inputText.replace(/222/gi, "&#304;");
        inputText = inputText.replace(/444/gi, "&#350;");
        inputText = inputText.replace(/666/gi, "&#286;");
        inputText = inputText.replace(/555/gi, "&#287;");
        inputText = inputText.replace(/333/gi, "&#351;");
        inputText = inputText.replace(/111/gi, "&#305;");
        
        inputText = inputText.replace(/___/gi, " ");
        inputText = inputText.replace(/yyy/gi, "&#214;");
        inputText = inputText.replace(/xxx/gi, "&#246;");
        inputText = inputText.replace(/000/gi, "&#199;");
        inputText = inputText.replace(/999/gi, "&#231;");
        inputText = inputText.replace(/888/gi, "&#220;");
        inputText = inputText.replace(/777/gi, "&#252;");
        inputText = inputText.replace(/%20/gi, " ");
    }
    
    return inputText;
}

function makeStringTransferable(inputText)
{
	if(inputText.length>0) 
	{
		var i = 0;
		var temp = "";
		for(i=0; i<inputText.length; i++)
		{
			if (inputText.charCodeAt(i) == 304)
			{
				// we have an i
				inputText = inputText.substring(0, i) + '%DD' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 350)
			{
				// we have a S
				inputText = inputText.substring(0, i) + '%DE' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 286)
			{
				// we have a G
				inputText = inputText.substring(0, i) + '%D0' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 287)
			{
				// we have a G
				inputText = inputText.substring(0, i) + '%F0' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 351)
			{
				// we have a S
				inputText = inputText.substring(0, i) + '%FE' + inputText.substring(i+1, inputText.length);
			} 
			else if (inputText.charCodeAt(i) == 305)
			{
				// we have an I
				inputText = inputText.substring(0, i) + '%FD' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 252)
			{
				// we have an ü
				inputText = inputText.substring(0, i) + '%FC' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 220)
			{
				// we have an Ü
				inputText = inputText.substring(0, i) + '%DC' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 231)
			{
				// we have a ç
				inputText = inputText.substring(0, i) + '%E7' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 199)
			{
				// we have a Ç
				inputText = inputText.substring(0, i) + '%C7' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 246)
			{
				// we have an ö
				inputText = inputText.substring(0, i) + '%F6' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 214)
			{
				// we have an Ö
				inputText = inputText.substring(0, i) + '%D6' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charAt(i) == ' ')
			{
				// we have a space
				inputText = inputText.substring(0, i) + '___' + inputText.substring(i+1, inputText.length);
			}
			else if (inputText.charCodeAt(i) == 39)
			{
				// we have an '
				inputText = inputText.substring(0, i) + '' + inputText.substring(i+1, inputText.length);
			}
		}
		
		return inputText;
	} else
	{
		return "";
	}
}    

function getHighlighted(e)
{
    if (textboxFocused <= 0)
    {
    	highlightedText = (document.all) ? document.selection.createRange().text : document.getSelection();
    	highlightedText += '';
    	if(highlightedText.length>0) 
    	{
    		highlightedText = makeStringTransferable(highlightedText);
    		lookupWord(highlightedText);
    		return true;
    	} else
    	{
    		return false;
    	}
    }
}

function AutoSuggestControl(oTextbox, oProvider)
{
    this.cur = -1;
    this.layer = null;
    this.provider = oProvider;
    this.textbox = oTextbox;
    
    this.init();
}

AutoSuggestControl.prototype.selectRange = function(iStart, iLength)
{
    if (this.textbox.createTextRange)
    {
        var oRange = this.textbox.createTextRange();
        oRange.moveStart("character", iStart);
        oRange.moveEnd("character", iLength-this.textbox.value.length);
        oRange.select();
    } 
    else if (this.textbox.setSelectionRange)
    {
        this.textbox.setSelectionRange(iStart, iLength);
    }
    
    this.textbox.focus();
};

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);
    }
};

AutoSuggestControl.prototype.autosuggest = function(aSuggestions, bTypeAhead)
{
    if (aSuggestions.length > 1)
    {
        if (bTypeAhead)
        {
            this.typeAhead(aSuggestions[0]);
        }
        this.showSuggestions(aSuggestions);
    }
    else
    {
        this.cur = -1;
        this.hideSuggestions();
    }
};

AutoSuggestControl.prototype.charButtonPressed = function (char)
{
    addChar(char);
};

AutoSuggestControl.prototype.handleKeyDown = function(oEvent)
{
    switch(oEvent.keyCode)
    {
        case 38: //up arrow
            if (oEvent.preventDefault)
            {
                oEvent.preventDefault();
            }
            this.previousSuggestion();
            break;
        case 40: //down arrow
            if (oEvent.preventDefault)
            {
                oEvent.preventDefault();
            }
            this.nextSuggestion();
            break;
        case 13: //enter
            this.hideSuggestions();
            break;
        case 27: //esc
            var previousValue = this.textbox.value;
            this.cur = -1;
            this.hideSuggestions();
            this.textbox.value = previousValue;
            break;
        case 17: //ctrl
            ctrlPressed = true;
            break;
        case 32: //space
            if (ctrlPressed)
            {
                sTextToComplete = this.textbox.value;
                if (oEvent.preventDefault)
                {
                    oEvent.preventDefault();
                }
            }
            break;
    }
    return true;
};

function SuggestionProvider()
{
}

SuggestionProvider.prototype.requestSuggestions = function(oAutoSuggestControl, bTypeAhead)
{
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
    
    ///
    if (sTextboxValue.length >= 1)
    {
        // determine suggestions
        for (var i=0; i < this.states.length; i++) 
        {
            if (this.states[i].indexOf(sTextboxValue) == 0) 
            {
                aSuggestions.push(this.states[i]);
            }
        }
    }
    
    oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
};

AutoSuggestControl.prototype.nextSuggestion = function () 
{
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) 
    {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
    }
};

AutoSuggestControl.prototype.previousSuggestion = function () 
{
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) 
    {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
    }
};

AutoSuggestControl.prototype.highlightSuggestion = function(oSuggestionNode)
{
    for (var i=0; i<this.layer.childNodes.length; i++)
    {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode)
        {
            oNode.className = "current";
        }
        else if (oNode.className == "current")
        {
            oNode.className = "";
        }
    }
};

AutoSuggestControl.prototype.createDropDown = function()
{
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    if (navigator.userAgent.indexOf("Firefox")!=-1)
    {
	    // browser is FF
	    this.layer.style.width = this.textbox.offsetWidth-4;
    }
    else
    {
	    // browser is not FF
	    this.layer.style.width = this.textbox.offsetWidth;
    }
    
    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.preventDefault)
        {
            oEvent.preventDefault();
        }
        
        if (oEvent.type == "mousedown")
        {
            oThis.textbox.value = oTarget.childNodes[1].nodeValue;
            oThis.cur = -1;
            oThis.hideSuggestions();
            lookupWord(makeStringTransferable(oThis.textbox.value));
            oThis.textbox.focus();
        }
        else if (oEvent.type == "mouseover")
        {
            oThis.highlightSuggestion(oTarget.parentNode.parentNode.parentNode.parentNode);
        }
//        else if (oEvent.type == "mouseup")
//        {
//            oThis.textbox.focus();
//        }
    };
    
    document.body.appendChild(this.layer);
};

AutoSuggestControl.prototype.hideSuggestions = function()
{
    var cSuggestionNodes = this.layer.childNodes;
    if (cSuggestionNodes.length > 0 && this.cur <= cSuggestionNodes.length-1 && this.cur > -1) 
    {
        var oNode = cSuggestionNodes[this.cur];
        var sFieldValue = oNode.firstChild.innerHTML;

        var cellStart = sFieldValue.indexOf("<!--1-->");
        var cellEnd = sFieldValue.indexOf("<!--2-->");

        var iStart = cellStart+8;
        var iLength = cellEnd-iStart;
        sFieldValue = sFieldValue.substr(iStart, iLength);
        this.textbox.value = sFieldValue;
    }
    
    this.layer.style.visibility = "hidden";
    this.cur = -1;
};

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.showSuggestions = function(aSuggestions)
{
    if ( aSuggestions[0].toLowerCase() == trimWord(document.getElementById("lookup_word_id").value.toLowerCase()) )
    {
        var oDiv = null;
        this.layer.innerHTML = "";

        for (var i=1; i<aSuggestions.length; i++)
        {
            oDiv = document.createElement("div");
            oDiv.innerHTML = "<TABLE width='95%'><tr><td style='font-size: 1.1em;'><!--1-->" + makeStringViewable(aSuggestions[i]) + "<!--2--></td><TD align='right'><font color='green' size='-1'>" + aSuggestions[++i] + " lookups</font></td></tr></table>";
            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";
    }
    else
    {
        this.hideSuggestions();
        //alert (aSuggestions[0].toLowerCase() + " --- " + trimWord(document.getElementById("lookup_word_id").value.toLowerCase()));
    }
};

function RemoteWordSuggestions() 
{
    if (typeof XMLHttpRequest != "undefined") 
    {
        this.http = new XMLHttpRequest();
    } 
    else if (typeof ActiveXObject != "undefined") 
    {
        this.http = new ActiveXObject("MSXML2.XmlHttp");
    } 
    else {
        alert("No XMLHttpRequest object available. This functionality will not work.");
    }
}

RemoteWordSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl, bTypeAhead)
{
    oAutoSuggestControl.cur = -1;
    oAutoSuggestControl.hideSuggestions();
    var sTextboxValue = oAutoSuggestControl.textbox.value;
    
    ///
    if (sTextboxValue.length > 0)
    {
        var oHttp = this.http;

        if (oHttp)
        {
            oHttp.abort();
        }
        
        var sSeed = makeStringTransferable(oAutoSuggestControl.textbox.value);
        var sSuggestionStr = '[]';
        
        if (aSuggestionCache[sSeed] != null && aSuggestionCache[sSeed].length > 0)
        {
            sSuggestionStr = aSuggestionCache[sSeed];
            
            var aSuggestions = eval(sSuggestionStr);
            if (aSuggestions != null)
            {
                if (aSuggestions.length > 1)
                {
                    oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
                }
            }
        }
        else
        {
            var sURL = "suggest_words.php?prefix=" + sSeed;
        
            oHttp.open("get", sURL , true);
            oHttp.onreadystatechange = function () 
            {
                if (oHttp.readyState == 4) 
                {
                    sSuggestionStr = oHttp.responseText;
                    var aSuggestions = eval(sSuggestionStr);
                    if (aSuggestions != null)
                    {
                        if (aSuggestions.length > 1)
                        {
                            var currentPrefix = aSuggestions[0];
                            if ( currentPrefix.toLowerCase() == trimWord(document.getElementById("lookup_word_id").value).toLowerCase() )
                            {
                                oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
                                aSuggestionCache[sSeed] = sSuggestionStr;
                            }
                            else
                            {
                                oAutoSuggestControl.hideSuggestions();
                            }
                        }
                    }
                }
            };
            
            oHttp.send(null);
        }
    }
    else
    {
        oAutoSuggestControl.hideSuggestions();
    }
};

function addChar(chr, autoSuggest)
{
	document.lookup_form.word.value += chr;
	document.lookup_form.word.focus();
    autoSuggest.provider.requestSuggestions(autoSuggest, false)
}

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();
        textboxFocused = 0;
    };
    
    this.createDropDown();
};
