// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();

// 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 prog 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) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}
 
// read a file from the server
function processfilaktion(fnc, idfiakt, userid)   // processfilaktion(1, 20, 65);
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
      // create the params string
      var params = "fnc=" + fnc + "&idfiakt=" + idfiakt + "&userid=" + userid + "&nochachid=" + Math.random();
      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", joomlabaseuri + "aktf_myfunctions_ajax.php?" + params, true);
      xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function processprodaktion(fnc, idFiliale, idProdukt, erstdat, userid)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
      // create the params string
      var params = "fnc=" + fnc + "&idfiliale=" + idFiliale + "&idprodukt=" + idProdukt + "&erstdat=" + erstdat +
				   "&userid=" + userid  + "&nochachid=" + Math.random();
      // initiate the asynchronous HTTP request 
      xmlHttp.open("GET",  joomlabaseuri + "aktf_myfunctions_ajax.php?" + params, true);
      xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function processprodukt(fnc, idProdukt, userid)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
      // create the params string
      var params = "fnc=" + fnc + "&idprodukt=" + idProdukt + "&userid=" + userid + "&nochachid=" + Math.random();;
      // initiate the asynchronous HTTP request
      xmlHttp.open("GET",  joomlabaseuri + "aktf_myfunctions_ajax.php?" + params, true);
      xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function setalarm(userid, sparte, id)
{
    // only continue if xmlHttp isn't void
    if (xmlHttp)
    {
        // try to connect to the server
        try
        {
            // create the params string
            var params = "userid=" + userid + "&sparte=" + sparte + "&id=" + id + "&nochachid=" + Math.random();

            // initiate the asynchronous HTTP request
            xmlHttp.open("GET",  joomlabaseuri + "aktf_aktionsalarm_ajax.php?" + params, true);
            xmlHttp.onreadystatechange = handleRequestStateChange;
            xmlHttp.send(null);
        }
        // display the error in case of failure
        catch (e)
        {
            alert("Can't connect to server:\n" + e.toString());
        }
    }
}

function setalarmday(userid, day)
{
    // only continue if xmlHttp isn't void
    if (xmlHttp)
    {
        // try to connect to the server
        try
        {
            // create the params string
            var params = "userid=" + userid + "&day=" + day + "&nochachid=" + Math.random();

            // initiate the asynchronous HTTP request
            xmlHttp.open("GET",  joomlabaseuri + "aktf_aktionsalarmday_ajax.php?" + params, true);
            xmlHttp.onreadystatechange = handleRequestStateChange;
            xmlHttp.send(null);
        }
        // display the error in case of failure
        catch (e)
        {
            alert("Can't connect to server:\n" + e.toString());
        }
    }
}

function handleRequestStateChange() 
{
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponse();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}

// handles the response received from the server
function handleServerResponse()
{
  // retrieve the server's response packaged as an XML DOM object
  var xmlResponse = xmlHttp.responseXML;
  // catching potential errors with IE and Opera
  if (!xmlResponse || !xmlResponse.documentElement)
    throw("1-Invalid XML structure:\n" + xmlHttp.responseText);
 
  // catching potential errors with Firefox
  var rootNodeName = xmlResponse.documentElement.nodeName;
  if (rootNodeName == "parsererror") 
    throw("2-Invalid XML structure:\n" + xmlHttp.responseText);

  // getting the root element (the document element)
  xmlRoot = xmlResponse.documentElement;
  // testing that we received the XML document we expect
  if (rootNodeName != "response" || !xmlRoot.firstChild)
    throw("Invalid XML structure:\n" + xmlHttp.responseText);

  // the value we need to display is the child of the root <response> element
  responseText = xmlRoot.firstChild.data;

    if (responseText == "V2")
    {
        // aktion ermitteln
        aktion = xmlRoot.getElementsByTagName("aktion").item(0).firstChild.data;

        // aktionen verarbeiten
        if (aktion == "setalarmbutton") { alarmbutton("set",
                         xmlRoot.getElementsByTagName("sparte").item(0).firstChild.data,
                         xmlRoot.getElementsByTagName("id").item(0).firstChild.data) }
        else
        if (aktion == "delalarmbutton") { alarmbutton("del",
                         xmlRoot.getElementsByTagName("sparte").item(0).firstChild.data,
                         xmlRoot.getElementsByTagName("id").item(0).firstChild.data) }
        else
        if (aktion == "setalarmdaybutton") { alarmdaybutton("set",
                         xmlRoot.getElementsByTagName("day").item(0).firstChild.data,
                         xmlRoot.getElementsByTagName("daymsg").item(0).firstChild.data) }
        else
        if (aktion == "delalarmdaybutton") { alarmdaybutton("del",
                         xmlRoot.getElementsByTagName("day").item(0).firstChild.data,
                         xmlRoot.getElementsByTagName("daymsg").item(0).firstChild.data) }
    }
    else
    {
        // display the user message
        var text = "merken";
        var bildname  = "bild"+responseText.substring(1);
        var image = joomlabaseuri + "images/einkaufsliste_rauf.png";
        var buttontext = "Produkt auf die Einkaufsliste schreiben!";
        
        if (responseText.charAt(0) == "i")
        {
            text = "gemerkt";
            image = joomlabaseuri + "images/einkaufsliste_weg.png";
            var buttontext = "Produkt von der Einkaufsliste löschen!";
        }  
        var button=document.getElementById(responseText.substring(1));
        var button2=document.getElementById("b"+responseText.substring(1));
        var aktuellesProdukt=document.getElementById("aktuellesprodukt"); 
        
        if (document.getElementById(bildname)){
	        document.getElementById(bildname).src = image;
	        button.title = buttontext;
    	}
    	
        if (button && button2)
        {
            if (button.childNodes[0] && button2.childNodes[0])
            {	    
                button.childNodes[0].nodeValue=text;
	        	button2.childNodes[0].nodeValue=text;		
            }	  
            else 
            if (button.value && button2.value)
            {        
                button.value=text;
                button.title=buttontext;
                button2.value=text;
                button2.title=buttontext;
                
            }	  
            else //if (button.innerHTML)
            {
                button.innerHTML=text;
                button2.innerHTML=text;
            }
        } 
        else 
        if (button)
        {
            if (button.childNodes[0])
            {	    
                button.childNodes[0].nodeValue=text;	
            }	  
            else 
            if (button.value)
            {        
                button.value=text;
                button.title=buttontext;
            }	  
            else //if (button.innerHTML)
            {
                button.innerHTML=text;		
            }
        } 
        else if (aktuellesProdukt)
        {
            aktuellesProdukt.value=responseText;
        }
    }
}

function alarmbutton(aktion, sparte, id) 
{
    var buttonname = "alarm_" + sparte + "_" + id;
    var bildname = "alarmbild_" + sparte + "_" + id;
    var button = document.getElementById(buttonname);
    var alarmbezname = "alarmbez_" + sparte + "_" + id;
    var alarmbez = document.getElementById(alarmbezname).firstChild.nodeValue;

    if (aktion == "set")
    {
        replaceButtonText(buttonname,"löschen");
        button.style.backgroundColor="yellowgreen";
        document.getElementById(bildname).src = joomlabaseuri + "images/aktionsalarm/alarm_on.png";
        alarmmsg = "Alarm für " + alarmbez + " gesetzt !!!";
    }	  
    else
    {
        replaceButtonText(buttonname,"setzen");
        button.style.backgroundColor="lightgrey";
        document.getElementById(bildname).src = joomlabaseuri + "images/aktionsalarm/alarm_off.png";
        alarmmsg = "Alarm für " + alarmbez + " gelöscht !!!";
    }

    replaceDivText("alarmtext", alarmmsg);
}

function alarmdaybutton(aktion, day, daymsg) 
{
    var buttonname = "alarmday_" + day;
    var bildname = "alarmdaybild_" + day;
    var button = document.getElementById(buttonname);

    if (aktion == "set")
    {
        replaceButtonText(buttonname,"löschen");
        button.style.backgroundColor="yellowgreen";
        document.getElementById(bildname).src = joomlabaseuri + "images/aktionsalarm/alarm_on.png";
    }	  
    else
    {
        replaceButtonText(buttonname,"setzen");
        button.style.backgroundColor="lightgrey";
        document.getElementById(bildname).src = joomlabaseuri + "images/aktionsalarm/alarm_off.png";
    }

    replaceDivText("alarmtext", daymsg);
}

function replaceButtonText(buttonId, text)
{
    if (document.getElementById)
    {
        var button=document.getElementById(buttonId);
        if (button)
        {
            if (button.childNodes[0])
            {
                button.childNodes[0].nodeValue=text;
            }
            else 
            if (button.value)
            {
                button.value=text;
            }
            else //if (button.innerHTML)
            {
                button.innerHTML=text;
            }
        }
    }
}

function replaceDivText(divId, text)
{
    if (document.getElementById)
    {
        var divelement = document.getElementById(divId);
        if (divelement)
        {
            if (divelement.childNodes[0])
            {
                divelement.childNodes[0].nodeValue = text;
            }
            else 
            if (divelement.value)
            {
                divelement.value = text;
            }
            else
            {
                divelement.innerHTML = text;
            }
        }
    }
}

