var getFunctionsUrl = "/get_suggestion.php?pre=";
/* the keyword for which an HTTP request has been initiated */
var httpRequestKeyword = "";
/* the last keyword for which suggests have been requested */
var userKeyword = "";
/* number of suggestions received as results for the keyword */
var suggestions = 0;
/* the maximum number of characters to be displayed for a suggestion */
var suggestionMaxLength = 40;
/* flag that indicates if the up or down arrow keys were pressed the last time a keyup event occurred  */
var isKeyUpDownPressed = false;
/* flag that indicates if there are results for the current requested keyword*/
var hasResults = false;
/* the currently selected suggestion (by arrow keys or mouse)*/
var position = -1;
// when set to true, display detailed error messages
var debugMode = true;
/* the XMLHttp object for communicating with the server */
var xmlHttpGetSuggestions = createXmlHttpRequestObject();
/* prvek input, ke kteremu je naseptavac*/
var inputElement = "city";
/* objekt pro inputElement */
var oKeyword = null;
/* id div prvku, do ktereho se vkladaji navrhy*/
var suggestElement = "suggest";
/* objekt pro suggestElement */
var oSuggest = null;
/* jmeno classy pro styl zvyrazneneho radku*/
var highlightrow = "act";
/* casovace */
var hTimer = null;	// skryti suggest
var dTimer = null;	// data - stazeni a zobrazeni
/* the identifier used to cancel the evaluation with the clearTimeout method. */
var timeoutId = -1;

/* the onload event is handled by our init function */
window.onload = init;

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() {
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try  {
    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");
    for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
      try { 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  if(!xmlHttp) alert("Error creating the XMLHttpRequest object.");
  else return xmlHttp;
}

function init() {  
  oKeyword = document.getElementById(inputElement);    
  oSuggest = document.getElementById(suggestElement); 
  // prevent browser from starting the autofill function
  oKeyword.setAttribute("autocomplete", "off");  
  // reset the content of the keyword and set the focus on it
  // oKeyword.value = "";
//  oKeyword.focus();
  // na input box priradime obsluhu stisku klaves
  oKeyword.onkeyup = handleKeyUp;	// pismena
  oKeyword.onkeydown = handleKeyDown;  // sipky a spol.
  // pokud ztrati focus, tak se schova suggest
  oKeyword.onblur = function() { hTimer = setTimeout("hideSuggestions()", 500); };
} 

/* initiate HTTP request to retrieve suggestions for the current keyword */
function getSuggestions(keyword) {  
  if(keyword != "" && !isKeyUpDownPressed) {
      if(xmlHttpGetSuggestions) { 
        try {
          /* if the XMLHttpRequest object isn't busy with a previous request... */
          if(xmlHttpGetSuggestions.readyState == 4 || xmlHttpGetSuggestions.readyState == 0) {    
            httpRequestKeyword = keyword;
            userKeyword = keyword;
			/* mimo mesta beru i okres a kraj */
			var district = (document.getElementById("district") == null)?0:document.getElementById("district").value;
			var region = (document.getElementById("s_region") == null)?0:document.getElementById("s_region").value;
            xmlHttpGetSuggestions.open("GET", getFunctionsUrl + encode(keyword) + "&d=" + district + "&r=" + region, true);  /* ZDE SE VYTVARI DOTAZ */
            xmlHttpGetSuggestions.onreadystatechange = handleGettingSuggestions; 
            xmlHttpGetSuggestions.send(null);
          }
          // if the XMLHttpRequest object is busy...
          else {
            userKeyword = keyword;
            if(timeoutId != -1) clearTimeout(timeoutId);          
            // try again in 0.5 seconds     
            timeoutId = setTimeout("getSuggestions(userKeyword);", 500);
          }
        }
        catch(e) {
          displayError("Can't connect to server:\n" + e.toString());
        }
      }
  }
}

/* transforms all the children of an xml node into an array */
function xmlToArray(resultsXml) {
  var resultsArray= new Array();  
  for(i=0;i<resultsXml.length;i++)
    resultsArray[i] = resultsXml.item(i).firstChild.data;
  return resultsArray;
}

/* handles the server's response containing the suggestions for the requested keyword  */
function handleGettingSuggestions() {
  //if the process is completed, decide what to do with the returned data
  if (xmlHttpGetSuggestions.readyState == 4) {
    // only if HTTP status is "OK"
    if (xmlHttpGetSuggestions.status == 200) { 
      try {
        updateSuggestions();
      }
      catch(e) {
        displayError(e.toString()); 
      }  
    } 
    else {
      displayError("There was a problem retrieving the data:\n" + xmlHttpGetSuggestions.statusText);
    }       
  }
}

/* function that processes the server's response */
function updateSuggestions() {
  // retrieve the server's response 
  var response = xmlHttpGetSuggestions.responseText;
  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 = xmlHttpGetSuggestions.responseXML.documentElement;
  // initialize the new array of functions' names
  nameArray = new Array();
  // check to see if we have any results for the searched keyword
  if(response != null && response.childNodes.length) {
    /* we retrieve the new functions' names from the document element as an array */
    nameArray = xmlToArray(response.getElementsByTagName("name"));       		// v xml jsou hodnoty v atributu name
  }
  // check to see if other keywords are already being searched for
  if(httpRequestKeyword == userKeyword) {
    displayResults(httpRequestKeyword, nameArray);
  }
}

/* populates the list with the current suggestions */
function displayResults(keyword, results_array) {  
	clearTimeout(hTimer);
	hTimer = null;
	oSuggest.innerHTML = "";
  // if the array of results is empty display a message
  if(results_array.length == 0) {
    oSuggest.innerHTML = "<li>Zadny zaznam pro <strong>" + keyword + "</strong></li>";
    hasResults = false;
    suggestions = 0;
  } else {
    position = -1;
    isKeyUpDownPressed = false;
    hasResults = true;
    suggestions = results_array.length;
    // loop through all the results and generate the HTML list of results
    for(var i=0; i<results_array.length; i++) {
		var oLi = document.createElement("li");
		if(results_array[i].length <= suggestionMaxLength)
			oLi.innerHTML = results_array[i];
		else
			oLi.innerHTML = results_array[i].substring(0,suggestionMaxLength);
		oLi.onmouseover = OnMouseOver;
		oLi.onmouseout = OnMouseOut;
		oLi.onclick = onClick;
		oLi.position = i;
		oSuggest.appendChild(oLi);
    }
  }
  oSuggest.style.height = ((suggestions)?suggestions*14:14)+"px";
  oSuggest.style.display = "block";
}

function checkForChanges() {
  var keyword = oKeyword.value;
  if(keyword == "") {
    hideSuggestions();
    userKeyword = "";
    httpRequestKeyword = "";
  }
  if((userKeyword != keyword) && (!isKeyUpDownPressed)) getSuggestions(keyword);
}

function getKey(e) {
  e = (!e) ? window.event : e;
  code = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0));
  return code;
}

function keyUpDown(code) {
    if(code == 40) {  // down
		if(position >= 0) oldLI = oSuggest.childNodes[position];
        newLI = oSuggest.childNodes[position+1];        
        if(position >= 0 && position < suggestions-1) oldLI.className = "";
        if(position < suggestions - 1) {
          newLI.className = highlightrow;
          position++;
        }     
    }
    if(code == 38) {  // up
		if(position == -1) newLI = oSuggest.childNodes[suggestions - 1];
		if(position >= 0) oldLI = oSuggest.childNodes[position];
        if(position > 0) newLI = oSuggest.childNodes[position - 1];        
        if(position > 0 && position <= suggestions - 1) oldLI.className = "";
        if(position > 0) {
          newLI.className = highlightrow;
          position--;
        } 
		if(position == -1) {
          newLI.className = highlightrow;
       	  position = suggestions - 1;				
		}
    }
    isKeyUpDownPressed = true;        
}

function handleKeyDown(e) {
	code = getKey(e);
    isKeyUpDownPressed = false; 
	// pri enteru nebo sipka vpravo vlozi hodnotu
    if((code == 13 || code == 39) && position >= 0) { updateKeywordValue(position); hideSuggestions(); return false; }
    // if the down or up arrow is pressed we go to the next suggestion
    if(code == 40 || code == 38) { keyUpDown(code); return true; }
	// pri ESC schova okno
    if(code == 27) { hideSuggestions(); return true; }
}

function handleKeyUp(e) {
	code = getKey(e);
	// DEL neb BACKSPACE if(code == 8 || code == 46) ;  // zpracujeme normalne
    // check to see we if are interested in the current character
    if ((code < 46 && code != 8)  || (code >= 112 && code <= 123)) return true;	
	// byl stisknut normalni znak
	clearTimeout(dTimer);
	dTimer = null;
 	dTimer = setTimeout("checkForChanges()", 250);
}

function updateKeywordValue(position) {
  if(position < 0) return false;
  var value = oSuggest.childNodes[position].innerHTML;
  oKeyword.value = (value);
}

function OnMouseOver() {
	handleOnMouseOver(this);
}
function handleOnMouseOver(oLi) {
  if(position >= 0) oSuggest.childNodes[position].className = "";
  oLi.className = highlightrow;  
  position = oLi.position;
}

function OnMouseOut() {
	handleOnMouseOut(this);
}
function handleOnMouseOut(oLi) {
  if(position >= 0) oSuggest.childNodes[position].className = "";
  oLi.className = "";
  position = -1;
}

function onClick() {
	handleOnClick(this);
}
function handleOnClick(oLi) {
	updateKeywordValue(oLi.position);
	hideSuggestions();
	oKeyword.focus();
}

function encode(uri) {
  if(encodeURIComponent) return encodeURIComponent(uri);
  if(escape) return escape(uri);
}

function hideSuggestions() {
  oSuggest.style.display = "none";  
}

function displayError(message) {
  alert("Error accessing the server! "+(debugMode ? "\n" + message : ""));
}

