// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address
// when set to true, display detailed error messages
var showErrors = true;
// initialize the validation requests cache
var cache = new Array();

var internal_function = 0;

var serverAddress = "ajax/handle_text.php";

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
        // will store the reference to the XMLHttpRequest object
        var xmlHttp;
        // this should work for all browsers except IE6 and older
        try
        {
                // try to create XMLHttpRequest object
                xmlHttp = new XMLHttpRequest();
        }
        catch(e)
        {
        // assume IE6 or older
                var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
                // try every id until one works
                for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
                {
                        try
                        {
                                // try to create XMLHttpRequest object
                                xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
                        }
                        catch (e) {} // ignore potential error
                }
        }
        // return the created object or display an error message
        if (!xmlHttp)
                displayError("Error creating the XMLHttpRequest object.");
        else
        return xmlHttp;
}

function refresh_select(inputValue)
{
        internal_function = 3;

        // only continue if xmlHttp isn't void
        if (xmlHttp)
        {
                // if we received non-null parameters, we add them to cache in the
                // form of the query string to be sent to the server for validation
                if (inputValue)
                {
                        // encode values for safely adding them to an HTTP request query string
                        inputValue = encodeURIComponent(inputValue);
                        internal_function_tmp = encodeURIComponent(internal_function);
                        // add the values to the queue
                        cache.push("inputValue=" + inputValue + "&internal_function=" + internal_function_tmp);
                }
                // try to connect to the server
                try
                {
                        // continue only if the XMLHttpRequest object isn't busy
                        // and the cache is not empty
                        if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
                                && cache.length > 0)
                        {
                                // get a new set of parameters from the cache
                                var cacheEntry = cache.shift();

                                // make a server request to validate the extracted data
                                xmlHttp.open("POST", serverAddress, true);
                                xmlHttp.setRequestHeader("Content-Type",
                                                 "application/x-www-form-urlencoded");
                                xmlHttp.onreadystatechange = handleRequestStateChange;
                                xmlHttp.send(cacheEntry);
                        }
                }

                catch (e)
                {
                        // display an error when failing to connect to the server
                        displayError(e.toString());
                }
        }
}

// the function handles the validation for any form field
function select_text(inputValue)
{
        internal_function = 1;

        // only continue if xmlHttp isn't void
        if (xmlHttp)
        {
                // if we received non-null parameters, we add them to cache in the
                // form of the query string to be sent to the server for validation
                if (inputValue)
                {
                        // encode values for safely adding them to an HTTP request query string
                        inputValue = encodeURIComponent(inputValue);
                        internal_function_tmp = encodeURIComponent(internal_function);
                        // add the values to the queue
                        cache.push("inputValue=" + inputValue + "&internal_function=" + internal_function_tmp);
                }
                // try to connect to the server
                try
                {
                        // continue only if the XMLHttpRequest object isn't busy
                        // and the cache is not empty
                        if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
                                && cache.length > 0)
                        {
                                // get a new set of parameters from the cache
                                var cacheEntry = cache.shift();

                                // make a server request to validate the extracted data
                                xmlHttp.open("POST", serverAddress, true);
                                xmlHttp.setRequestHeader("Content-Type",
                                                 "application/x-www-form-urlencoded");
                                xmlHttp.onreadystatechange = handleRequestStateChange;
                                xmlHttp.send(cacheEntry);
                        }
                }

                catch (e)
                {
                        // display an error when failing to connect to the server
                        displayError(e.toString());
                }
        }
}

function delete_text()
{
        inputValue = document.getElementById("ID_termin_text").value;
        internal_function = 4;

        // only continue if xmlHttp isn't void
        if (xmlHttp)
        {
                // if we received non-null parameters, we add them to cache in the
                // form of the query string to be sent to the server for validation
                if (inputValue)
                {
                        // encode values for safely adding them to an HTTP request query string
                        inputValue = encodeURIComponent(inputValue);
                        internal_function_tmp = encodeURIComponent(internal_function);
                        // add the values to the queue
                        cache.push("inputValue=" + inputValue + "&internal_function=" + internal_function_tmp);
                }
                // try to connect to the server
                try
                {
                        // continue only if the XMLHttpRequest object isn't busy
                        // and the cache is not empty
                        if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
                                && cache.length > 0)
                        {
                                // get a new set of parameters from the cache
                                var cacheEntry = cache.shift();

                                // make a server request to validate the extracted data
                                xmlHttp.open("POST", serverAddress, true);
                                xmlHttp.setRequestHeader("Content-Type",
                                                 "application/x-www-form-urlencoded");
                                xmlHttp.onreadystatechange = handleRequestStateChange;
                                xmlHttp.send(cacheEntry);
                        }
                }

                catch (e)
                {
                        // display an error when failing to connect to the server
                        displayError(e.toString());
                }
        }
}

function new_text()
{
        inputValue = document.getElementById("ID_termin").value;
        internal_function = 5;

        // only continue if xmlHttp isn't void
        if (xmlHttp)
        {
                // if we received non-null parameters, we add them to cache in the
                // form of the query string to be sent to the server for validation
                if (inputValue)
                {
                        // encode values for safely adding them to an HTTP request query string
                        inputValue = encodeURIComponent(inputValue);
                        internal_function_tmp = encodeURIComponent(internal_function);
                        // add the values to the queue
                        cache.push("inputValue=" + inputValue + "&internal_function=" + internal_function_tmp);
                }
                // try to connect to the server
                try
                {
                        // continue only if the XMLHttpRequest object isn't busy
                        // and the cache is not empty
                        if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
                                && cache.length > 0)
                        {
                                // get a new set of parameters from the cache
                                var cacheEntry = cache.shift();

                                // make a server request to validate the extracted data
                                xmlHttp.open("POST", serverAddress, true);
                                xmlHttp.setRequestHeader("Content-Type",
                                                 "application/x-www-form-urlencoded");
                                xmlHttp.onreadystatechange = handleRequestStateChange;
                                xmlHttp.send(cacheEntry);
                        }
                }

                catch (e)
                {
                        // display an error when failing to connect to the server
                        displayError(e.toString());
                }
        }
}

function save_text(inputValue_ID, inputValue_sort, inputValue_text, inputValue_ID_termin)
{
        internal_function = 2;

        // only continue if xmlHttp isn't void
        if (xmlHttp)
        {
                // if we received non-null parameters, we add them to cache in the
                // form of the query string to be sent to the server for validation
                if (inputValue_ID)
                {
                        // encode values for safely adding them to an HTTP request query string
                        inputValue_sort = encodeURIComponent(inputValue_sort);
                        inputValue_text = encodeURIComponent(inputValue_text);
                        inputValue_ID = encodeURIComponent(inputValue_ID);
                        inputValue_ID_termin = encodeURIComponent(inputValue_ID_termin);
                        internal_function_tmp = encodeURIComponent(internal_function);
                        // add the values to the queue
                        cache.push("inputValue_sort=" + inputValue_sort + "&inputValue_text=" + inputValue_text + "&inputValue_ID=" + inputValue_ID + "&inputValue_ID_termin=" + inputValue_ID_termin + "&internal_function=" + internal_function_tmp);
                }
                // try to connect to the server
                try
                {
                        // continue only if the XMLHttpRequest object isn't busy
                        // and the cache is not empty
                        if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
                                && cache.length > 0)
                        {
                                // get a new set of parameters from the cache
                                var cacheEntry = cache.shift();

                                // make a server request to validate the extracted data
                                xmlHttp.open("POST", serverAddress, true);
                                xmlHttp.setRequestHeader("Content-Type",
                                                 "application/x-www-form-urlencoded");
                                xmlHttp.onreadystatechange = handleRequestStateChange;
                                xmlHttp.send(cacheEntry);
                        }
                }

                catch (e)
                {
                        // display an error when failing to connect to the server
                        displayError(e.toString());
                }
        }
}

// function that handles the HTTP response
function handleRequestStateChange()
{
        // when readyState is 4, we read the server response
        if (xmlHttp.readyState == 4)
        {
                // continue only if HTTP status is "OK"
                if (xmlHttp.status == 200)
                {
                        try
                        {
                                // read the response from the server
                                readResponse();
                        }
                        catch(e)
                        {
                                // display error message
                                displayError(e.toString());
                        }
                }
                else
                {
                        // display error message
                        displayError(xmlHttp.statusText);
                }
        }
}

// read server's response
function readResponse()
{
        // retrieve the server's response
        var response = xmlHttp.responseText;

        // server error?
        if (response.indexOf("ERRNO") >= 0
                || response.indexOf("error:") >= 0
                || response.length == 0)
                throw(response.length == 0 ? "Server error." : response);
        // get response in XML format (assume the response is valid XML)
        responseXml = xmlHttp.responseXML;
        // get the document element
        xmlDoc = responseXml.documentElement;
// alert(internal_function + '!' + response);
        // Anzeige von Ergebnissen
        switch (internal_function)
        {
                case 1:
                        document.getElementById("ID_sort").value = xmlDoc.getElementsByTagName("sort")[0].firstChild.data;
                        document.getElementById("info").value = xmlDoc.getElementsByTagName("info")[0].firstChild.data;
                        document.getElementById("tmp_ID").value = xmlDoc.getElementsByTagName("tmp_ID")[0].firstChild.data;

                        document.getElementById("InfoMsg").innerHTML = "Daten k&ouml;nnen nun ge&auml;ndert werden.";

                        setTimeout("select_text();", 500);
                        break;
                case 2:
                        // Funktion zum REFRESH des Auswahlfelds aufrufen
                        selected_ID = xmlDoc.getElementsByTagName("result")[0].firstChild.data;

                        document.getElementById("InfoMsg").innerHTML = "Daten gesichert.";

                        refresh_select(document.getElementById('ID_termin').value);
                        break;
                case 3:
                        // REFRESH auswerten
                        resultsXmlID = xmlDoc.getElementsByTagName("ID");
                        resultsXml = xmlDoc.getElementsByTagName("NAME");

                        //Leeren
                        Ziel = document.getElementById('ID_termin_text');
                        for (var Nr = Ziel.length; Nr > 0;)
                                Ziel.options[--Nr] = null

                        // füllen
                        for(i=0;i<resultsXml.length;i++) {
                                Ziel.options[i] = new Option(resultsXml.item(i).firstChild.data, resultsXmlID.item(i).firstChild.data)
                                if (resultsXmlID.item(i).firstChild.data == selected_ID) {
                                        Ziel.options[i].selected = true;
                                        // tmp_ID setzten, für INSERT wichtig
                                        document.getElementById("tmp_ID").value = selected_ID;
                                } else {
                                        Ziel.options[i].selected = false;
                                }
                        }
                        break;
                case 4:
                        // DELETE
                        // Funktion zum REFRESH des Auswahlfelds aufrufen
                        selected_ID = xmlDoc.getElementsByTagName("result")[0].firstChild.data;

                        document.getElementById("InfoMsg").innerHTML = "Eintrag gel&ouml;scht.";

                        document.getElementById("info").value = "";
                        document.getElementById("tmp_ID").value = "X";

                        refresh_select(document.getElementById('ID_termin').value);
                        break;
                case 5:
                        // NEW
                        selected_ID = 0;
                        refresh_select(document.getElementById('ID_termin').value);

                        // Umweg, um MAX-Sort zu finden
                        max_sort = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
                        max_sort = parseInt(max_sort) + 1;

                        document.getElementById("InfoMsg").innerHTML = "Daten k&ouml;nnen nun angelegt werden.";

                        document.getElementById("info").value = "";
                        document.getElementById("tmp_ID").value = "X";
                        document.getElementById("ID_sort").value = max_sort;
                        break;
        }
}
