var getFunctionsUrl = "../etc/suggest.php5?keyword=";
var phpHelpUrl=""; //"http://www.php.net/manual/en/function.";
var httpRequestKeyword = "";
var userKeyword = "";
var suggestions = 0;
var suggestionMaxLength = 30;
var isKeyUpDownPressed = false;
var autocompletedKeyword = "";
var hasResults = false;
var timeoutId = -1;
var position = -1;
var oCache = new Object();
var minVisiblePosition = 0;
var maxVisiblePosition = 9;
var debugMode = true;
var xmlHttpGetSearchSuggestions = createXmlHttpRequestObject();
var keyWordChoosen;
var flagSearch = 0;
var startTxt = "Szukaj słów kluczowych ..."

window.onload = init;


function swText()
{
	var oIn = document.getElementById('keyword');
	if(flagSearch == 0)
	{
		oIn.className = 'keyword';
		oIn.value = startTxt;
		flagSearch = 1;
	}
	else
	{
		oIn.className = 'keywordFocus';
		oIn.value = '';
		flagSearch = 0;
	}	
}

function createXmlHttpRequestObject()
{
  var xmlHttp;

  try
  {
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    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("Błąd podczas tworzenia obiektu.");
  else 
    return xmlHttp;
}


function init()
{

  var oKeyword = document.getElementById("keyword");

  oKeyword.setAttribute("autocomplete", "off");  
  oKeyword.value = "";

  swText();
  setTimeout("checkForChanges()", 500);
} 



function addToCache(keyword, values)
{
  oCache[keyword] = new Array();

  for(i=0; i<values.length; i++)
    oCache[keyword][i] = values[i];
}


function checkCache(keyword)
{
  if(oCache[keyword])
    return true;

  for(i=keyword.length-2; i>=0; i--)
  {
    var currentKeyword = keyword.substring(0, i+1);

    if(oCache[currentKeyword])
    {
      var cacheResults = oCache[currentKeyword];

      var keywordResults = new Array();
      var keywordResultsSize = 0;            

      for(j=0;j<cacheResults.length;j++)
      {
        if(cacheResults[j].indexOf(keyword) == 0)               
          keywordResults[keywordResultsSize++] = cacheResults[j];
      }
      addToCache(keyword, keywordResults);      
      return true;  
    }
  }
  return false;
}


function getSuggestions(keyword)
{  
  if(keyword != "" && !isKeyUpDownPressed)
  {
    isInCache = checkCache(keyword);

    if(isInCache == true)          
    {   
      httpRequestKeyword=keyword;
      userKeyword=keyword;     
      displayResults(keyword, oCache[keyword]); 
    }
    else    
    {    
      if(xmlHttpGetSearchSuggestions)
      { 
        try
        {
          if (xmlHttpGetSearchSuggestions.readyState == 4 || 
              xmlHttpGetSearchSuggestions.readyState == 0) 
          {    
            httpRequestKeyword = keyword;
            userKeyword = keyword;
            xmlHttpGetSearchSuggestions.open("GET", getFunctionsUrl + encode(keyword), true);
            xmlHttpGetSearchSuggestions.onreadystatechange = handleGettingSuggestions; 
            xmlHttpGetSearchSuggestions.send(null);
          }

          else
          {
            userKeyword = keyword;

            if(timeoutId != -1)
              clearTimeout(timeoutId); 
  
            timeoutId = setTimeout("getSuggestions(userKeyword);", 500);
          }
        }
        catch(e)
        {
          displayError("Nie mogę polączyć się z serwerem:\n" + e.toString());
        }
      }
    }
  }
}


function xmlToArray(resultsXml)
{
  var resultsArray= new Array();  

  for(i=0;i<resultsXml.length;i++)
    resultsArray[i]=resultsXml.item(i).firstChild.data;

  return resultsArray;
}


function handleGettingSuggestions()
{
  if (xmlHttpGetSearchSuggestions.readyState == 4) 
  {
    if (xmlHttpGetSearchSuggestions.status == 200) 
    { 
      try
      {
        updateSuggestions();
      }
      catch(e)
      {
        displayError(e.toString());
      }  
    } 
    else
    {
      displayError("Wystąpił problem podczas pobierania danych:\n" +
        xmlHttpGetSearchSuggestions.statusText);
    }       
  }
}


function updateSuggestions()
{
  var response = xmlHttpGetSearchSuggestions.responseText;

  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0
    || response.length == 0)
    throw(response.length == 0 ? "Pusta odpowiedź serwera." : response);

  response = xmlHttpGetSearchSuggestions.responseXML.documentElement;
  nameArray = new Array();

  if(response.childNodes.length)
  {
    nameArray = xmlToArray(response.getElementsByTagName("name"));
  }
  if(httpRequestKeyword == userKeyword)    
  {
    displayResults(httpRequestKeyword, nameArray);
  }
  else
  {
    addToCache(httpRequestKeyword, nameArray); 
  }
}


function displayResults(keyword, results_array)
{  
  var div = "<table>";

  if(!oCache[keyword] && keyword)
    addToCache(keyword, results_array);
  if(results_array.length == 0)
  {
     div += "<tr><td>Nie znaleziono słów kluczowych rozpoczynających się od <strong>" + keyword +
           "</strong></td></tr>";

    hasResults = false;
    suggestions = 0;
  }

  else
  {
    position = -1;
    isKeyUpDownPressed = false;
    hasResults = true;
    suggestions = oCache[keyword].length;

    for(var i=0; i<oCache[keyword].length; i++)
    {  
      crtFunction = oCache[keyword][i];
      crtFunctionLink = crtFunction;

      while(crtFunctionLink.indexOf("_") !=-1)
        crtFunctionLink = crtFunctionLink.replace("_","-");
        
		//div += "<tr id='tr" + i + "' onclick='' onmouseover='handleOnMouseOver(this);' " +
		//"onmouseout='handleOnMouseOut(this);'>" + "<td align='left'><a id='a" + i +
	//	"' name='"+crtFunction+"' href='javascript:sendTag(\""+crtFunction+"\");";
		
		div += "<tr id='tr" + i + "' onmouseover='handleOnMouseOver(this);' " +
		"onmouseout='handleOnMouseOut(this);' onclick='handleOnMouseClick(this);'>" + "<td align='left'><a id='a" + i +
		"' name='"+crtFunction+"' href='#'";
		
		
      if(crtFunction.length <= suggestionMaxLength)
      {
        div += "'><b>" + crtFunction.substring(0, httpRequestKeyword.length) + "</b>"
        div += crtFunction.substring(httpRequestKeyword.length, crtFunction.length) +
          "</a></td></tr>";
      }
      else
      {
        if(httpRequestKeyword.length < suggestionMaxLength)
        {
          div += "'><b>" + crtFunction.substring(0, httpRequestKeyword.length) + "</b>"
          div += crtFunction.substring(httpRequestKeyword.length, suggestionMaxLength) +
            "</a></td></tr>";
        }
        else
        {
          div += "'><b>" + crtFunction.substring(0,suggestionMaxLength) +
            "</b></td></tr>"          
        }
      }
    }
  }
  div += "</table>";
  
  var oSuggest = document.getElementById("suggest");
  var oScroll = document.getElementById("scroll");

  oScroll.scrollTop = 0;

  oSuggest.innerHTML = div;
  oScroll.style.visibility = "visible";

  if(results_array.length > 0)
    autocompleteKeyword();
}

//Nowa funkcja po zmianach strutkury

function sendTag(tag)
{
	document.searchf.keyword.value = tag;
}

function checkForChanges()
{
  var keyword = document.getElementById("keyword").value;
 
  if(keyword == "")
  {
    hideSuggestions();

    userKeyword="";
    httpRequestKeyword="";
  }
  setTimeout("checkForChanges()",  500);

  if((userKeyword != keyword) && (autocompletedKeyword != keyword) &&
    (!isKeyUpDownPressed) && (keyword != startTxt))
    getSuggestions(keyword);
}


function handleKeyUp(e)
{	
	e = (!e) ? window.event : e;
	
	target = (!e.target) ? e.srcElement : e.target;
	if(target.nodeType == 3) 
		target = target.parentNode;

	code = (e.charCode) ? e.charCode :
	 ((e.keyCode) ? e.keyCode :
	 ((e.which) ? e.which : 0));

	if(e.type == "keyup")
	{    
		isKeyUpDownPressed = false;
		
		if((code < 13 && code != 8) || (code >=14 && code < 32) ||
			(code >= 33 && code <= 46 && code != 38 && code != 40) ||
			(code >= 112 && code <= 123)) 
		{

		}
  		else
  		{
			if(code == 13)
			{
				if(position>=0)
				{
					sendTag(document.getElementById("a" + position).name);
				}
				else if(position == -1);
					this.submit();
			}
			else
			{
				if(code == 40)
				{
					newTR=document.getElementById("tr"+(++position));
					oldTR=document.getElementById("tr"+(--position));
			
					if(position>=0 && position<suggestions-1)
						oldTR.className = "";
					if(position < suggestions - 1)
					{
						newTR.className = "highlightrow";
						updateKeywordValue(newTR);
						position++;
					}
					e.cancelBubble = true;
					e.returnValue = false;
					isKeyUpDownPressed = true;

					if(position > maxVisiblePosition)
					{
			  			oScroll = document.getElementById("scroll");
			 		 	oScroll.scrollTop += 18;
			  			maxVisiblePosition += 1;
			 			minVisiblePosition += 1;
					}
				}
				else if(code == 38)
				{
					newTR=document.getElementById("tr"+(--position));
					oldTR=document.getElementById("tr"+(++position));

					if(position>=0 && position <= suggestions - 1)
					{
						oldTR.className = "";
					}
					if(position > 0)
					{
						newTR.className = "highlightrow";
						updateKeywordValue(newTR);
						position--;
						if(position<minVisiblePosition)
						{
							oScroll = document.getElementById("scroll");
							oScroll.scrollTop -= 18;
							maxVisiblePosition -= 1;
							minVisiblePosition -= 1;
						}
					}
					else
						if(position == 0)
								position--;
					e.cancelBubble = true;
					e.returnValue = false;
					isKeyUpDownPressed = true;
				}
			}
		}
	}
}


function updateKeywordValue(oTr)
{
  var oKeyword = document.getElementById("keyword");
  var crtLink = document.getElementById("a" + oTr.id.substring(2,oTr.id.length)).name;
  oKeyword.value = unescape(crtLink.substring(0, crtLink.length));
}


function deselectAll()
{ 
  for(i=0; i<suggestions; i++)
  {
    var oCrtTr = document.getElementById("tr" + i);
    oCrtTr.className = "";
  }
}

function handleOnMouseClick(oTr)
{
	updateKeywordValue(oTr);
	var form = document.search;
	form.submit();
	
}

function handleOnMouseOver(oTr)
{
  deselectAll();
  oTr.className = "highlightrow";
  position = oTr.id.substring(2, oTr.id.length);
}


function handleOnMouseOut(oTr)
{
  oTr.className = "";
  position = -1;
}


function encode(uri)
{
  if (encodeURIComponent) 
  {
    return encodeURIComponent(uri);
  }

  if (escape) 
  {
    return escape(uri);
  }
}


function hideSuggestions()
{
  var oScroll = document.getElementById("scroll");
  oScroll.style.visibility = "hidden";  
}


function selectRange(oText, start, length)
{  
  if (oText.createTextRange) 
  {
    //IE
    var oRange = oText.createTextRange(); 
    oRange.moveStart("character", start); 
    oRange.moveEnd("character", length - oText.value.length); 
    oRange.select();
  }
  else 
    // FF
    if (oText.setSelectionRange)
    {
      oText.setSelectionRange(start, length);
    }
  oText.focus();
}


function autocompleteKeyword()
{
  var oKeyword = document.getElementById("keyword");
  
  position=0;
  deselectAll();
  document.getElementById("tr0").className="highlightrow";
  updateKeywordValue(document.getElementById("tr0"));
  selectRange(oKeyword,httpRequestKeyword.length,oKeyword.value.length);
  autocompletedKeyword=oKeyword.value;
}


function displayError(message)
{
  alert("Błąd podczas dostępu do serwera! " + (debugMode ? "\n" + message : ""));
}