/**
 * Copyright 2006-2010 by Jeremy March.  All rights reserved.
 */
var reqCOM;
var defCache = new Array();
var defCacheLength = 0;
var defCacheLimit = 500;
var useDefCache = true;

function act(id, lexicon, word, word_or_root)
{
    if (word_or_root == "Word")
        getDef(id, lexicon, word);
}

function getDef(id, lexicon, word)
{
    var skipCache = 0;
    var addWordLinks = 0;

    //the random number id needed for ie--it would ask for the same page twice
	var url = 'wordserv.php?id=' + id + '&lexicon=' + lexicon + '&skipcache=' + skipCache + '&addwordlinks=' + addWordLinks + '&x=' + Math.random();
    //new Ajax.Updater('lsjdef', url, { method: 'get' });
	if (!useDefCache || !defCheckCache(lexicon, id))
        loadXMLDoc(url);
    else
        return;

	document.getElementById("lsjdef").innerHTML = "<center>Requesting definition...</center>";
}

function setWord(response)
{
	var def = response.getElementsByTagName("def");
    var lexicon = response.getElementsByTagName("lexicon");
    var id = response.getElementsByTagName("word_id");
    var word = response.getElementsByTagName("word");
    var lemma = response.getElementsByTagName("lemma");
    
	var con = document.getElementById("lsjdef");
    
    if (lexicon)
        lexicon = lexicon[0].firstChild.data;
    
    var attr = "<br/><br/><div id='attrib' style='text-align:center;'>";
    if (lexicon && lexicon == "greek")
    {
        attr += "<a href='http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus:text:1999.04.0057' style='color:blue;'>Liddell, Scott, and Jones</a> ";
        attr += "<a href='http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus%3Atext%3A1999.04.0057%3Aentry%3D";
    }
    else if (lexicon && lexicon == "slater")
    {
        attr += "<a href='http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus:text:1999.04.0072' style='color:blue;'>Slater's <i>Lexicon to Pindar</i></a> ";
        attr += "<a href='http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus%3Atext%3A1999.04.0072%3Aentry%3D";    
    }
    else if (lexicon && lexicon == "latin")
    {
        attr += "<a href='http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus:text:1999.04.0059' style='color:blue;'>Lewis and Short</a> ";
        attr += "<a href='http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus%3Atext%3A1999.04.0059%3Aentry%3D";    
    }
    attr += escape(lemma[0].firstChild.data);
    attr += "' style='color:blue;'>entry</a> courtesy of the<br/>";
    attr += "<a href='http://www.perseus.tufts.edu' style='color:blue;'><img alt='' src='images/new-rm-logo2.gif' height='25' width='25' style='vertical-align: middle; border: 0;'/>Perseus Digital Library</a>";
    attr += "</div>";
    //attr += "</div>";    

	con.innerHTML = def[0].firstChild.data + attr;	//the firstChild is the CDATA node
    
    if (useDefCache)
    {
        defAddResultToCache(lexicon, id[0].firstChild.data, response);
    }    
}

function processReqChange()
{
	try {

	if (reqCOM.readyState == 4)
	{
		if (reqCOM.status == 200)	// if "OK"
		{
			var response = reqCOM.responseXML.documentElement;

			var method = response.getElementsByTagName('method')[0].firstChild.data;
			eval(method + '(response)');
		}
		else
		{
			//change this--should not be alert()
            if (debug)
                alert("There was a problem retrieving the XML data:\n" + reqCOM.statusText);
		}
	}

	} 
	catch(e)
	{ 
		reqCOM.abort();  
        if (debug)
            alert("Exception in processReqChange: " + e.message);  
	}
}

function loadXMLDoc(url) 
{
	reqCOM = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

	if (reqCOM)
	{
		reqCOM.onreadystatechange = processReqChange;
		reqCOM.open("GET", url, true);
		reqCOM.send(null);
	}
}

function defview(node)
{
    this.node = mode;
    this.requestDef = null;
    this.onDefReceived = null;
}

function defCheckCache(lexicon, queryKey)
{
    queryKey = lexicon + queryKey;
    if (defCache && defCache[queryKey])
    {
        //alert("here");
        setWord(defCache[queryKey].str);
        return true;
    }
    else
    {
        return false; //not cached, request it
    }
}

function defAddResultToCache(lexicon, queryKey, str)
{
    queryKey = lexicon + queryKey;

    //if this query isn't in the cache
    if (!defCache[queryKey])
    {
        //if we're at the cacheLimit remove the oldest item 
        //use cacheLength because assoc arrays have no length property and we don't want to have to count them each time
        if (defCacheLimit && defCacheLength >= defCacheLimit)
        {
            var prev = null;
            for (var x in defCache)
            {
                if (!defCache.hasOwnProperty(x))
                    continue;
                    
                if (prev == null || defCache[x].time < defCache[prev].time)
                    prev = x;
            }
            if (prev)
            {
                //alert("delete");
                defCacheLength--;
                delete defCache[prev];
            }
        }
        defCacheLength++;
        defCache[queryKey] = new Array();
        defCache[queryKey].str = str;
        defCache[queryKey].time = new Date().getTime();
    }
    else
    {
        //if it is in the cache, update the timestamp
        defCache[queryKey].time = new Date().getTime();
    }
}

