
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
var ServiceURI = "ajax/ajax.php";


// the id of the div
var buttondiv = "SaveDiv";



// +eveything starts here
function init(lang,action)
{
  var language = lang;
  // test if user has browser that supports native XSLT functionality
  if(window.XMLHttpRequest && window.XSLTProcessor && window.DOMParser)
  {
    // load
    getForm(lang);
    return;
  }
  // test if user has Internet Explorer with proper XSLT support
  if (window.ActiveXObject && createMsxml2DOMDocumentObject())
  {
    // load
    getForm(lang);
    return;
  }
  // if browser functionality testing failed, alert the user
  alert("Your browser doesn't support the necessary functionality.");
}



function createMsxml2DOMDocumentObject()
{
  // will store the reference to the MSXML object
  var msxml2DOM;
  // MSXML versions that can be used for our grid
  var msxml2DOMDocumentVersions = new Array("Msxml2.DOMDocument.6.0",
                                            "Msxml2.DOMDocument.5.0",
                                            "Msxml2.DOMDocument.4.0");
  // try to find a good MSXML object
  for (var i=0; i<msxml2DOMDocumentVersions.length && !msxml2DOM; i++)
  {
    try
    {
      // try to create an object
      msxml2DOM = new ActiveXObject(msxml2DOMDocumentVersions[i]);
    }
    catch (e) {}
  }
  // return the created object or display an error message
  if (!msxml2DOM)
    alert("Please upgrade your MSXML version from \n" +
          "http://msdn.microsoft.com/XML/XMLDownloads/default.aspx");
  else
    return msxml2DOM;
}

// 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;
}

// loads the stylesheet from the server using a synchronous request
function loadStylesheet(action)
{
  // load the file from the server
  xmlHttp.open("GET", ServiceURI+"?action="+action, false);
  xmlHttp.send(null);
  // try to load the XSLT document
  if (this.DOMParser) // browsers with native functionality
  {
    var dp = new DOMParser();
    stylesheetDoc = dp.parseFromString(xmlHttp.responseText, "text/xml");
  }
  else if (window.ActiveXObject) // Internet Explorer?
  {
    stylesheetDoc = createMsxml2DOMDocumentObject();
    stylesheetDoc.async = false;
    stylesheetDoc.load(xmlHttp.responseXML);
  }
}




function secure_code_validate(language){
 var divbutton = document.getElementById("codeInput");
 if (divbutton){
	if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
     {
       var query = ServiceURI + "?action=validate_code_form&code="+divbutton.value+"&lang="+language;
       xmlHttp.open("GET", query, true);
       xmlHttp.onreadystatechange = handleResponse;
       xmlHttp.send(null);
    } }
 return;
}

// hole html formular mit dem code
function getForm(lang)
{
  // continue only if the XMLHttpRequest object isn't busy  var divbutton = document.getElementById("SaveDiv");
  if (!divbutton){
		return;  }
  else {
   if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
   {
    var query = ServiceURI + "?action=get_html_form_new&lang="+lang;
    xmlHttp.open("GET", query, true);
    xmlHttp.onreadystatechange = handleResponse;
    xmlHttp.send(null);
   }
  }
}

function make_submit_visible(){
	var divb = document.getElementById("saveSudokuButton");
    if (divb){
		divb.setAttribute('style','visibility:visible;');
		return;
    }}






// update one row in the grid if the connection is clear
function updateArticle(params)
{
  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
    var query = feedGridUrl + "?action=update";
    xmlHttp.open("POST", query, false); // hier : syncron
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send(encodeURI(params));
  }
}


// handle receiving the server response with a new page of products
function handleResponse()
{

  // if readyState is 4, we read the server response
  if (xmlHttp.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200)
    {
      // read the response
      response = xmlHttp.responseText;
      // server error?
      var divbutton = document.getElementById("SaveDiv");
 		if (divbutton){
		   divbutton.innerHTML = '';
		   if (response != 'true'){
		     divbutton.innerHTML = response;
		   }
		   else make_submit_visible(); 		}

      if (response.indexOf("ERRNO") >= 0
          || response.indexOf("error") >= 0
          || response.length == 0)
      {
        // display error message
        alert(response.length == 0 ? "Server serror." : response);
        // exit function
        return;
      }
     }
  }
}








// makes asynchronous request to load a new page
function loadGridPage(pageNo)
{

  // erzeuge eine globale Variable!
  modus = pageNo;

  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
    if (pageNo==1) var query = feedGridUrl + "?action=get_article_template";
    else
    var query = feedGridUrl + "?action=load_article&article_id=" + encodeURI(pageNo);
    xmlHttp.open("GET", query, true);
    xmlHttp.onreadystatechange = handleGridPageLoad;
    xmlHttp.send(null);
  }
}



// Bilderdownload kann fehlschalagen
function handle_error_onload(here){	if (_debugAll==true) alert("Load failure... \n Hier kann Fehlerbearbeitung beginnen!");}


////////////////
//Muell
///////////////


// handle receiving a response from the server when updating an article
function handleUpdatingArticle()
{
  // when readyState is 4, we read the server response
  if(xmlHttp.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if(xmlHttp.status == 200)
    {
      // read the response
      handleServerResponse();


       // die verwaltung der fehlermeldungen soll ueberdacht werden
      // server error?
      if (response.indexOf("ERRNO") >= 0
          || response.indexOf("error") >= 0
          || response.length == 0)
        alert(response.length == 0 ? "Server serror." : response);
      // if everything went well


    }
    else
    {
      // undo any changes in case of error
      //undo(editableId);
      alert("Error on server side.");
    }

  }
}

function handleServerResponse(){

	var xmlResponse = xmlHttp.responseXML;
	xmlRoot = xmlResponse.documentElement;

    // when readyState is 4, we read the server response
    if(xmlHttp.readyState == 4)
    {

	// Schritt 1. dafuer sorgen, dass alle Fehlermeldungen extrahiert und ggf. angezeigt werden
    var errors = xmlRoot.getElementsByTagName("error");
    var str = "Fehler:";
     for(var i=0; i<errors.length; i++){
     	str += errors[i].firstChild.data + '\n';
     }
    if (_debugAll) alert(str);

    // Schritt 2. Benutzer ueber das Ergebnis benachrichtigen
     errors = xmlRoot.getElementsByTagName("notice");
     str = '<span class="notice">Notice: ';
     for(var i=0; i<errors.length; i++){
     	str += errors[i].firstChild.data + '<br/>\n';
     }
        str += '</span><br/>';

     var statusDiv = document.getElementById("statusDiv");
     statusDiv.innerHTML = str;

     is_handler_free = true;
     var id_ = xmlRoot.getElementsByTagName("ID");
     id = id_[0].firstChild.data; // das soll globale var bleiben!
     alert(id);
   }
}











///////////////

// update one row in the grid if the connection is clear
function _send_binary_depricated(params)
{
  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
    var query = feedGridUrl + "?action=save_picture";
    xmlHttp.open("POST", query, true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.onreadystatechange = handleUpdatingArticle;
    xmlHttp.send(params);
  }
}


