/*
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You can get a copy of this license at http://www.gnu.org/licenses/gpl.txt.
*/

var NoMoreSuggestion = new Array(); // Size of the last unique suggestion
NoMoreSuggestion["small"] = -1;
NoMoreSuggestion["big"] = -1;


function setDivContent(box, content) {
	document.getElementById(box + "Suggestions").innerHTML = content;
}


function suggestions(box) {
	var l = document.getElementById(box + "Word").value.length;
	
	if ((l >= 3) && ((NoMoreSuggestion[box] == -1) || (l < NoMoreSuggestion[box]))) {
		var xhr=null;
		
		if (window.XMLHttpRequest) { 
			xhr = new XMLHttpRequest();
		}
		else if (window.ActiveXObject) 
		{
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}

		xhr.onreadystatechange = function() { displayResult(box, xhr); };
		xhr.open("GET", "../api/suggestions/?word=" + encodeURI(document.getElementById(box + "Word").value), true);
		xhr.send(null);
		
		NoMoreSuggestion[box] = -1;
	}
	
	if (l < 3) {
		setDivContent(box, "");
		NoMoreSuggestion[box] = -1;
	}
}


function displayResult(box, xhr) {
	if (xhr.readyState == 4) {
		var docXML= xhr.responseXML;
		var s = "";
		
		if (docXML != null) {
			var items = docXML.getElementsByTagName("word");
			
			if (items.length>0) {
				s = "\n\t\t\t\t<ol>\n";
				for (i=0;i<items.length;i++) {
					var word = items.item(i).firstChild.data;
					s = s + "\t\t\t\t\t<li><a  class=\"mot\" href=\"../translate/?word=" + encodeURI(word) + "\" />" + word + "</a></li>\n";
				}
				s = s + "\t\t\t\t</ol>\n\t\t\t";
		
				setDivContent(box, s);
			}
			if ((document.getElementById(box + "Word").value.length == 3) && (items.length<=0)) {
				setDivContent(box, "\n\t\t\t\t<p><em>Pas de suggestion.</em></p>\n\t\t\t");
			}
			if (items.length<=1) {
				NoMoreSuggestion[box] = document.getElementById(box + "Word").value.length;
			}
		}
	}
}

