var getResultURL = "http://smarteo.viaaurea.cz/js/ajax/GetByAJAX.php?SQLquery=";

var SQLquery;
var targetItemInputType;
var targetItemID;
var SQLvalueToReplace;

/* the identifier used to cancel the evaluation with the clearTimeout method. */
var timeoutId1 = -1;

var debugMode = true;
/* the XMLHttp object(s) for communicating with the server */
var xmlHttpGetResults = 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;
} // createXmlHttpRequestObject()

/* transforms all the children of an xml node into an array */
function xmlToArray(resultsXml) {
  // initiate the resultsArray
  var resultsArray = new Array();  
  // loop through all the xml nodes retrieving the content  
  for(i=0;i<resultsXml.length;i++) {
    resultsArray[i] = new Array();
    for(j=0;j<resultsXml.item(i).childNodes.length;j++) {
      resultsArray[i][resultsXml.item(i).childNodes.item(j).tagName] = resultsXml.item(i).childNodes.item(j).firstChild.data;
    }
  }
  // return the node's content as an array
  return resultsArray;
} // xmlToArray

// getResults1
function getResults(p_SQLquery, p_targetItemInputType, p_targetItemID, p_SQLvalueToReplace) {
  SQLquery = p_SQLquery.replace(/%replace%/, p_SQLvalueToReplace);
  targetItemInputType = p_targetItemInputType;
  targetItemID = p_targetItemID;
  SQLvalueToReplace = p_SQLvalueToReplace;

  if(xmlHttpGetResults) { 
    try {
      // if the XMLHttpRequest object isn't busy with a previous request...
      if (xmlHttpGetResults.readyState == 4 || xmlHttpGetResults.readyState == 0) {    
          xmlHttpGetResults.open("GET", getResultURL + encode(SQLquery), true);
          xmlHttpGetResults.onreadystatechange = handleGettingResults; 
          xmlHttpGetResults.send(null);
      }
      // if the XMLHttpRequest object is busy...
      else {      
        // clear any previous timeouts already set
        if(timeoutId != -1)
          clearTimeout(timeoutId);          
        // try again in 0.6 seconds     
        timeoutId = setTimeout("getResults('"+p_SQLquery+"', '"+p_targetItemInputType+"', '"+p_targetItemID+"', '"+p_SQLvalueToReplace+"');", 600);
      }
    }
    catch(e) {
      displayError("Can't connect to server:\n" + e.toString());
    }
  }    
} // getResults

// handleGettingResults
function handleGettingResults() {
  //if the process is completed, decide what to do with the returned data
  if (xmlHttpGetResults.readyState == 4) {
    // only if HTTP status is "OK"
    if (xmlHttpGetResults.status == 200) { 
      try {
        // process the server's response
        updateResults();
      }
      catch(e) {
        // display the error message
        displayError("handleGettingResults: " + e.toString()); 
      }  
    } 
    else {
      displayError("getResults: There was a problem retrieving the data:\n" + 
                   xmlHttpGetResults.statusText);
    }       
  }
} // handleGettingResults

// updateResults
function updateResults() {
  // retrieve the server's response 
  var response = xmlHttpGetResults.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0) {
    throw(response.length == 0 ? "Void server response." : response);
  }  
  // retrieve the document element
  response = xmlHttpGetResults.responseXML.documentElement;
  // initialize the new array of functions' names
  var nameArray = new Array();
  // check to see if we have any results for the searched okres
 
  if(response.childNodes.length) {
    /* we retrieve the new functions' names from the document element as an array */
    nameArray = xmlToArray(response.getElementsByTagName("rslt"));       
  }
  // check to see if other okress are already being searched for
  returnResults(nameArray);
} // updateResults1

function returnResults(nameArray) {  
  if(targetItemInputType == 'text') {
    document.getElementById(targetItemID).value = nameArray[0]['label'];
  } else if(targetItemInputType == 'select') {
    var selement = document.getElementById(targetItemID);
    
    clear_selectbox(targetItemID);
    
    if(nameArray.length == 0) {
      selement.length++;
      selement.options[selement.options.length-1].value = 0;
      selement.options[selement.options.length-1].text = '- není na výběr -';
    } else if(nameArray.length == 1) { 
      selement.length++;
  		  selement.options[selement.options.length-1].value = nameArray[0]['id'];
  		  selement.options[selement.options.length-1].text = nameArray[0]['label'];    
    } else {
      selement.length++;
      selement.options[selement.options.length-1].value = 0;
      selement.options[selement.options.length-1].text = '- vyberte -';
    
      for(i=0;i<nameArray.length;i++) {
  		  selement.length++;
  		  selement.options[selement.options.length-1].value = nameArray[i]['id'];
  		  selement.options[selement.options.length-1].text = nameArray[i]['label'];
  		  
		  }
    } 
  }  
}

/* function that escapes a string */
function encode(uri) {
  if (encodeURIComponent) {
    return encodeURIComponent(uri);
  }

  if (escape) {
    return escape(uri);
  }
} // encode

/* function that displays an error message */
function displayError(message)
{
  // display error message, with more technical details if debugMode is true
  alert("©patně zadaný údaj! "+
        (debugMode ? "\n" + message : ""));
}

function clear_selectbox(id) {
  // clear selectbox
  var e = document.getElementById(id);
  e.selected = null;
  for (c=0;c<e.options.length;c++) {
    e.options[c] = null;
  }    
  
  if(e.options.length != 0) {
    clear_selectbox(id);
  }
      
}