var MINIMAL_TEXT_LENGTH = 3;
var WAIT_TO_FIRE_REQUEST = 500;
var HIGHLIGHTCLASS = 'auto2';

var targetTextBox;
var targetDiv;
var thread = null;
var xmlhttp;
var parameters;
var currentSelected;
function getSuggestions(url, targetTextBoxSource, targetDivName, prefixText, count, langId, e){

    targetTextBox = targetTextBoxSource;
    targetDiv = document.getElementById(targetDivName);

    var match = /[A-Za-z0-9]/.test(String.fromCharCode(e.keyCode)) || e.keyCode == "8";
    if(!match) return;
    
    //opoznienie przed wyslaniem requestu
    if(thread!=null) {clearTimeout(thread);}
    
    
    if(prefixText.length>=MINIMAL_TEXT_LENGTH ){  
         
        xmlhttp=null;

        if (window.XMLHttpRequest)
          {// code for all new browsers
            xmlhttp=new XMLHttpRequest();
          }
        else if (window.ActiveXObject)
          {// code for IE5 and IE6
             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        if (xmlhttp!=null)
          {
              xmlhttp.onreadystatechange=getSuggestionsState_Change;
              xmlhttp.open("POST",url,true);
              xmlhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
              
              parameters = '{"prefixText":"'+prefixText+'","count":'+count+',"contextKey":"'+langId+'"}';
              thread = setTimeout("xmlhttp.send(parameters);", WAIT_TO_FIRE_REQUEST);
              
          }
        else
          {
            alert("Your browser does not support XMLHTTP.");
          }
     }
}

function getSuggestionsState_Change()
{
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200)
    {// 200 = OK

        var resp = xmlhttp.responseText.replace('[', '').replace(']', '').split('","');
        for(var i=0; i<resp.length; i++){
            resp[i] = resp[i].replace(/"/g, '');
        }
        
        constructSuggestionsBox(resp);
    }
  else
    {
    alert("Problem retrieving XML data");
    }
  }
}

function constructSuggestionsBox(towns){
 
        targetDiv.innerHTML='';

       if(towns.length==1 && towns[0]=='') {
	
	  return;
	}
    

     //if(targetDiv!=null && targetDiv.style.display == 'none')
     //{
     //   targetDiv.style.display = 'block';

     //}
     
    var ul=document.createElement("ul")
    //ul.style.cssText ="padding:0; text-align:left; z-index:1; list-style:none; width:400px; color:#111; background:#e5e5e5 !important; opacity:0.90; filter:alpha(opacity=90); position:absolute;";
   

        for(var i = 0; i<towns.length;i++){
            var li = document.createElement("li");
            li.onmouseover=function () { highlightMe(this); };
            li.onmouseout=function () { highlightMeNot(this); };
            li.appendChild(document.createTextNode(towns[i].replace(/\\u0027/g, '\'')));
            ul.appendChild(li);
        }

    highlightMe(ul.firstChild);
    
    targetDiv.appendChild(ul);
	//targetDiv.appendChild(document.createElement("br"));
    document.onclick = hideSuggestionBox;
    document.onkeydown = performKeyDownEvent;
}

function highlightMe(listItem){
    if(currentSelected!=null)highlightMeNot(currentSelected);
    listItem.className = HIGHLIGHTCLASS;
    currentSelected = listItem;
}
function highlightMeNot(listItem){
    listItem.className = '';
    
}

function hideSuggestionBox(e)
{
       var evt = (e)?e:event;
       var theElem = (evt.srcElement)?evt.srcElement:evt.target;

         if(theElem.nodeName.toString() =='LI')
         {
            targetTextBox.value = theElem.innerHTML;
            targetDiv.innerHTML = '<ul style="visibility:hidden;" />';
		//targetDiv.style.display = 'none';
         }
         else
         {
            if(targetDiv != null) {
			targetDiv.innerHTML = '<ul style="visibility:hidden;" />';
			//targetDiv.style.display = 'none';
		}
         }     
         
         //wylaczamy eventy, aby nie brudzily
         document.onclick = '';
         document.onkeydown = '';  
}


function performKeyDownEvent(e){
    if(e == null) e = window.event;
    if(e.keyCode == "38"/*up arrow*/) {
        if(currentSelected.previousSibling!= null && currentSelected.previousSibling.nodeName.toString() == 'LI'){
            highlightMeNot(currentSelected);
            highlightMe(currentSelected.previousSibling);
        }
    }
    if(e.keyCode == "40" /*down arrow */){
        if(currentSelected.nextSibling!= null && currentSelected.nextSibling.nodeName.toString() == 'LI'){
            highlightMeNot(currentSelected);
            highlightMe(currentSelected.nextSibling);
        }
    }
    if(e.keyCode == "13" /*enter*/){
        //przepisujemy do textboxa co trzeba
        targetTextBox.value = currentSelected.innerHTML;
        //...i zamiatamy po sobie :)
        targetDiv.innerHTML = '';
        highlightMeNot(currentSelected);
        currentSelected = null;
        
        //wylaczamy eventy, aby nie brudzily
        document.onclick = '';
        document.onkeydown = '';
    }
}
