//Skrypty do AJAX-owego odpytywania się o słownik

//Zmienić dla stron w innych językach
var thesPleaseWaitMsg = "Proszę czekać...";
var communicationErrorMsg = "Błąd podczas pobierania odpowiedzi.";
var ajaxUnsupportedMsg = "Prawdopodobnie twoja przeglądarka nie wspiera wymaganej wersji JavaScript.";
var noResultsMsg = "Brak wyników.";
var groupNumFormat = "Grupa znaczeń nr {0}:";

//Towrzenie requestu w sposób w miarę niezależny od przeglądarki
function createXMLHttpRequest() {
    //IE oczywiście jest kompatybilny inaczej
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { /* nic */ }
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { /* nic */ }
    try { return new XMLHttpRequest(); } catch(e) { /* nic */ }
    return null;
}

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var Utf8 = {

	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

//Kodowanie łańcucha do UTF-8
function encodeUtf8(str) {
    //encodeURIComponent() i decodeURIComponent() nie działają w starszych przeglądarkach (IE 5)
    /*if (window.encodeURIComponent) {
        return unescape(encodeURIComponent(str));
    } else {
        co teraz?
    }*/
    return Utf8.encode(str);
}

//Dekodowanie łąńcucha z UTF-8
function decodeUtf8(str) {
    //encodeURIComponent() i decodeURIComponent() nie działają w starszych przeglądarkach (IE 5)
    /*if (window.decodeURIComponent) {
        return decodeURIComponent(escape(s));
    } else {
        co teraz?
    }*/
    return Utf8.decode(str);
}

//Escape'owanie znaków specjalnych dla HTML
function encodeHtml(str) {
    return str.replace("\"","&quot;").replace("'","&apos;").replace(">","&gt;").replace("<","&lt;")
}

//Tani formater - format("a{1}bc{0}","x","y")=="aybcx"
function format(str) {
    for(i = 1; i < arguments.length; i++) {
        str = str.replace("{"+(i-1)+"}",arguments[i]);
    }
    return str;
}

//Formatowanie odpowiedzi JSONowej z tezaurusa do HTML
function formatThesResults(results) {
    html = "";
    //Jeśli stary JS, nie obsługujący tablic
    //if (!results || !results.synonyms) {
    //    html = ajaxUnsupportedMsg;
    //    return html;
    //}
    if (results.synonyms.length > 0) {
        for (var i = 0; i < results.synonyms.length; i++) {
            if (results.synonyms.length > 1) {
                html+=format(groupNumFormat,i+1);
            }
            html+="<ul>\n";
            for (var j = 0; j < results.synonyms[i].length; j++) {
                html+="<li>"+encodeHtml(results.synonyms[i][j])+"</li>\n";
            }
            html+="</ul>\n";
        }
    } else {
        html = noResultsMsg;
    }
    return html;
}

//Wczytanie odpowiedzi ze słownika do wskazanego elementu
function thesIntoElem(dest,word,pathPrefix) {
    xmlHttp = createXMLHttpRequest();
    var elem = document.getElementById(dest);
    if (xmlHttp==null) {
        elem.innerHTML = ajaxUnsupportedMsg;
    } else {
        xmlHttp.open("GET",pathPrefix+"thesaurus-engine.php?print=1&word="+escape(encodeUtf8(word)),true);
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState==4) {
                if (xmlHttp.status==200) {
                    var result = new Function("return "+xmlHttp.responseText)();
                    //Na wszelki wypadek jeszcze raz ustawiamy treść pól z oryginalnym zapytaniem
                    //na podstawie komunikatu (mogło ich przyjśc wiele asynchronicznie)
                    fillQueryWord(result.word);
                    //UTF-8 otrzymanego z PHP nie trzeba odkodowywać, bo strona używa tego samego kodowania co PHP
                    elem.innerHTML = formatThesResults(result);
                } else {
                    elem.innerHTML = communicationErrorMsg;
                }
            } else {
                elem.innerHTML = thesPleaseWaitMsg;
            }
        }
        xmlHttp.send(null);
    }
}

//Specyficzne dla konkretnej strony - wypełnienie wartości odpowiednich pól treścią zapytania
function fillQueryWord(word) {
    document.getElementById("thesResultWithDesc").style.display = "block";
    document.getElementById("thesSourceWord").innerHTML = encodeHtml(word);
    document.thesForm.word.value = word;
}

function thesSample(word,pathPrefix) {
    fillQueryWord(word);
    thesIntoElem('thesResult',word,pathPrefix);
    //document.thesForm.word.focus();
    //document.thesForm.word.select();
}

//Funkcja tworzy przycisk, którego kliknięcie dopisuje wskazany tekst do wybranego pola tekstowego
function printAppenderButton(appendedText,field) {
    document.write("<input type=\"button\" value=\""+appendedText+"\" onClick=\"javascript:"+field+".value+='"+appendedText+"'; "+field+".focus();\">");
}

//Funkcja wypisuje przycisk za pomocą printAppenderButton() dla każdego kolejnego znaku z łańcucha
function printCharButtons(chars,field) {
    for (var i = 0; i < chars.length; i++) {
        //chars[i] nie działa w IE
        printAppenderButton(chars.charAt(i),field);
    }
}
