//window.onload = suggestBox();
var XMLMainElement = null;
var licznik = 0;
var wybrany = -1;
var tmpCode;
var tablicaLinkow;
var fraza = '';
var licznikBlednychLiter = 0;
var produkt = '';

function actionQuery(evt)
{
    var evt = (evt) ? evt : windows.event;
    suggestBox(evt);
    if (evt.keyCode != 8) //backspace
    {
        showBox(produkt);
    }
    checkKey(evt);
}
function ajaxInit ()
{	
        var XHR = null;

	try
	{
		XHR = new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{
			XHR = new ActiveXObject ("Msxsml2.XMLHTTP");
		}
		catch (e2)
		{
			try
			{
				XHR = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e3)
			{
				alert ("Błąd: Niestety twoja przeglądarka nie obsługuje AJAX'a!!!");
			}
		}
	}
       
	return XHR;	
}

function suggestBox(evt)
{
	var XHR = ajaxInit();

	if (XHR != null)
	{
            if (document.getElementById("searchQueryBrowser") == null)
                XHR.open("GET", "include/podpowiedzi.php"+"?wpis=' '", true); //true mowi ze asynchronicznie
            else
            {
                var url = document.getElementById("searchQueryBrowser").value.toLowerCase();
		  XHR.open("GET", "include/podpowiedzi.php"+"?wpis="+document.getElementById("searchQueryBrowser").value.toLowerCase(), true); //true mowi ze asynchronicznie
            }
		XHR.onreadystatechange = function()
		{
			if (XHR.readyState == 4)
			{
				if (XHR.status == 200)
				{
					XMLMainElement = XHR.responseXML.documentElement; //zwraca root z XML
                                        produkt = XMLMainElement.getElementsByTagName("Produkt");
                                        if (evt.keyCode == 8) //backspace
                                        {
                                            showBox(produkt);
                                        }
                                }
				else if (XHR.status == 0);
                                /*else
					alert ("Wystąpił błąd: "+XHR.status);*/
			}
		}

		XHR.send(null);
	}
}

function showBox(produkt)
{
   tablicaLinkow = [];
   var licznikPodpowiedzi = 0;
   var obj_form = document.forms.menuszukaj;
   var kolorowanieLicznik = 1;
   	if (XMLMainElement != null)
	{
		document.getElementById("suggestBoxField").style.visibility = 'hidden';
		document.getElementById("suggestBoxField").innerHTML = '';
                //if (wybrany == -1)
                //produkt = XMLMainElement.getElementsByTagName("Produkt");
                fraza = document.getElementById("searchQueryBrowser").value.toLowerCase();
                if (fraza.length >= 3)
                {
                    var suggestBoxField = document.getElementById("suggestBoxField");
                    for (var i = 0; i < produkt.length; i++)
                    {
                            if ((produkt[i].getElementsByTagName("Podpowiedz")[0].firstChild.nodeValue.toLowerCase().indexOf(fraza) >= 0 ||
                            produkt[i].getElementsByTagName("Tagi")[0].firstChild.nodeValue.toLowerCase().indexOf(fraza) >= 0) 
                                && produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue != 'Strona'
                                && produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue != 0)
                            {
                                    suggestBoxField.style.visibility = 'visible';
                                    var tmpDiv = document.createElement("div");
                                    tmpDiv.setAttribute("numer", kolorowanieLicznik);
                                    tmpDiv.setAttribute("rodzaj", "podpowiedz");

                                    if ((kolorowanieLicznik % 2) == 0)
                                         tmpDiv.className = 'podpowiedziParzyste';
                                    else
                                         tmpDiv.className = 'podpowiedzi';
                                    tmpDiv.onmouseover = function()
                                    {
                                          if (wybrany != -1)
                                            document.getElementById("suggestBoxField").childNodes[wybrany].className = 'podpowiedzi';
                                          this.className = 'podpowiedzihover';
                                    }

                                    tmpDiv.onmouseout = function()
                                    {
                                        var numerPod = this.getAttribute("numer");
                                        if ((numerPod % 2) == 0)
                                           this.className = 'podpowiedziParzyste';                                         
                                        else
                                           this.className = 'podpowiedzi';
                                            
                                    }

                                    tmpDiv.onclick = function()
                                    {
                                        var search = this.innerHTML;
                                        document.getElementById("searchQueryBrowser").value = wycinanieFrazyProd(usunTagi(search));
                                        obj_form.submit();                                        
                                    }

                                    document.onclick = function ()
                                    {
                                        document.getElementById("suggestBoxField").style.visibility = 'hidden';
                                    }
                                    var produktTmp = produkt[i].getElementsByTagName("Podpowiedz")[0].firstChild.nodeValue;
                                    var pytanieTmp = document.getElementById("searchQueryBrowser").value;
                                    
                                    var wyr = new RegExp (pytanieTmp,"gi");
                                    produktTmp = produktTmp.replace(wyr, '<b>'+pytanieTmp+'</b>');
                                    if (produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue == 0)
                                    {
                                        tmpDiv.innerHTML = produktTmp.toLowerCase()+'<span class="licznikPodpowiedzi">(0 produktów)<span>';
                                    }
                                    else
                                    {
                                        tmpDiv.innerHTML = produktTmp.toLowerCase()+'<span class="licznikPodpowiedzi">('
                                        +produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue+frazaIloscProd(produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue);
                                    }
                                    suggestBoxField.appendChild(tmpDiv);
                                    licznikPodpowiedzi++;
                                    kolorowanieLicznik++;
                            }
                            else if ((produkt[i].getElementsByTagName("Podpowiedz")[0].firstChild.nodeValue.toLowerCase().indexOf(fraza) >= 0 ||
                            produkt[i].getElementsByTagName("Tagi")[0].firstChild.nodeValue.toLowerCase().indexOf(fraza) >= 0)
                                && produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue == 'Strona'
                                && produkt[i].getElementsByTagName("Ilosc")[0].firstChild.nodeValue != 0)
                            {
                                    suggestBoxField.style.visibility = 'visible';
                                    
                                    var tmpDiv = document.createElement("div");
                                    tmpDiv.setAttribute("numer", kolorowanieLicznik);
                                    tmpDiv.setAttribute("rodzaj", "strona");

                                    if ((kolorowanieLicznik % 2) == 0)
                                         tmpDiv.className = 'podpowiedziStronyParzyste';
                                    else
                                         tmpDiv.className = 'podpowiedziStrony';

                                    tmpDiv.onmouseover = function()
                                    {
                                        if (wybrany > licznikPodpowiedzi)
                                          document.getElementById("suggestBoxField").childNodes[wybrany].className = 'podpowiedziStrony';
                                        this.className = 'podpowiedzihover';
                                    }

                                    tmpDiv.onmouseout = function()
                                    {
                                        var numerPod = this.getAttribute("numer");
                                        if ((numerPod % 2) == 0)
                                            this.className = 'podpowiedziStronyParzyste';
                                        else
                                            this.className = 'podpowiedziStrony';
                                    }

                                    tmpDiv.onclick = function()
                                    {                                        
                                        var search = wycinanieKluczaStrony(this.innerHTML);
                                        search = usunTagi(search);
                                        window.location.href = tablicaLinkow [search.toLowerCase()];
                                    }

                                    document.onclick = function ()
                                    {
                                        document.getElementById("suggestBoxField").style.visibility = 'hidden';
                                    }
                                    var stronaTmp = produkt[i].getElementsByTagName("Podpowiedz")[0].firstChild.nodeValue;
                                    var pytanieTmp = document.getElementById("searchQueryBrowser").value;
                                    
                                    var wyr = new RegExp (pytanieTmp,"gi");
                                    stronaTmp = stronaTmp.replace(wyr, '<b>'+pytanieTmp+'</b>');
                                    var wyr2 = /-/;
                                    stronaTmp = stronaTmp.replace(wyr2, ' ');                                    
                                    strona = usunTagi(wycinanieKluczaStrony(stronaTmp)).toLowerCase();
                                    tablicaLinkow[strona] = produkt[i].getElementsByTagName("Link")[0].firstChild.nodeValue;
                                    tmpDiv.innerHTML = stronaTmp.toLowerCase();
                                    suggestBoxField.appendChild(tmpDiv);
                                    kolorowanieLicznik++;
                            }
                    }
		}
	}
}

function frazaIloscProd (iloscProduktow)
{
    var fraza;
    if (iloscProduktow == '1')
        fraza = ' produkt)</span>';
    else if (iloscProduktow == '2' || iloscProduktow == '3' || iloscProduktow == '4')
        fraza = ' produkty)</span>';
    else
        fraza = ' produktów)</span>';

    return fraza;
}

function wycinanieKluczaStrony (fraza)
{
        fraza = fraza.replace (RegExp(" ","g"),'');
        return fraza;
}

function wycinanieFrazyProd (fraza)
{
        var wyr = /\([0-9]+\s+(produkt|produkty|produktów)\)/;
        fraza = fraza.replace (wyr, '');
        wyr = /<b>/;
        fraza = fraza.replace (wyr, '');
        wyr = /<\/b>/;
        fraza = fraza.replace (wyr, '');
        return fraza;
}

function checkKey(evt)
{
        var obj_form2 = document.forms.menuszukaj;

        liczbaPodpowiedzi = document.getElementById("suggestBoxField").childNodes.length;

	if (licznik == 0)
	{
		licznik = liczbaPodpowiedzi;
		wybrany = -1;
	}

	if (evt.keyCode != 13 && evt.keyCode != 38 && evt.keyCode != 40 && evt.keyCode != 8)
		licznik = 0;

	if (evt.keyCode == 40) //strzalka w dol
	{
		if (tmpCode == 'gora')
			licznik++;
		/*if (wybrany == (liczbaPodpowiedzi-1))
		{
		       licznik = -1;
                       wybrany = -1;
		}
		else if (wybrany == -1)
		{
			licznik = 0;
			wybrany = 0;		
		}
		else*/
			wybrany = licznik%liczbaPodpowiedzi;
		if (wybrany > -1)
			document.getElementById("suggestBoxField").childNodes[wybrany].className = "podpowiedzihover";
		licznik++;
		tmpCode = 'dol';
		//wstawTymczasowaPodpowiedz(wybrany);
	}
	else if (evt.keyCode == 38)//strzalka w gore
	{
 		if (tmpCode == 'dol')
			licznik--;	
		/*if (wybrany == 0)
		{
		       licznik = -1;
			wybrany = -1;
		}
		else if (wybrany == -1)
		{
			licznik = liczbaPodpowiedzi-1;
			wybrany = liczbaPodpowiedzi-1;
		}
		else	
		{*/
		licznik--;
		wybrany = licznik % liczbaPodpowiedzi;			
		
		if (wybrany > -1)
			document.getElementById("suggestBoxField").childNodes[wybrany].className = "podpowiedzihover";
		tmpCode = 'gora';
		//wstawTymczasowaPodpowiedz(wybrany);
	}
	else if (evt.keyCode == 13) //enter
        {
             document.getElementById("suggestBoxField").style.visibility = 'hidden';
                if (tmpCode != 'enter')
                {
                    if (wybrany == -1)
                    {
                        obj_form2.submit();
                    }
                    else
                    {
                        var search = '';
                        var dlugosc = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length;
                        var element = document.getElementById("suggestBoxField").childNodes[wybrany];
                        if (document.getElementById("suggestBoxField").childNodes[wybrany].getAttribute("rodzaj") == "podpowiedz")
                        {
                            /*if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 2 &&
                                document.getElementById("suggestBoxField").childNodes[wybrany].childElementCount == 1)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].nodeValue;
                                document.getElementById("searchQueryBrowser").value = wycinanieFrazyProd(usunTagi(search));
                                obj_form2.submit();
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 2)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].nodeValue;
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 3)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[2].firstChild.nodeValue;
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 4)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[2].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[3].firstChild.nodeValue;
                            }*/
                            search = pobierzFraze(element, dlugosc);
                            document.getElementById("searchQueryBrowser").value = wycinanieFrazyProd(usunTagi(search));
                            obj_form2.submit();
                        }
                        else
                        {
                            /*if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 2)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].nodeValue;
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 3)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[2].nodeValue;
                            }*/
                            search = pobierzFraze(element, dlugosc);
                            search = usunTagi(wycinanieKluczaStrony(search));
                            window.location.href = tablicaLinkow [search.toLowerCase()];
                        }
                    }
                    tmpCode = 'enter';                                        
                }
	}
	else if (evt.keyCode == 8) //backspace
	{
		licznik = 0;
		wybrany = -1;
		tmpCode = "backspace";
	}
	else if (evt.keyCode == 27) //escape
	{
		document.getElementById("suggestBoxField").style.visibility = 'hidden';
	}

}
function wyslijWyszukiwarke()
{
    var obj_form3 = document.forms.menuszukaj;
    
    if (wybrany == -1)
    {
        obj_form3.submit();
    }
    else
    {
        var search = '';
              if (document.getElementById("suggestBoxField").childNodes[wybrany].getAttribute("rodzaj") == "podpowiedz")
                        {
                            /*if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 2 &&
                                document.getElementById("suggestBoxField").childNodes[wybrany].childElementCount == 1)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].nodeValue;
                                document.getElementById("searchQueryBrowser").value = wycinanieFrazyProd(usunTagi(search));
                                obj_form2.submit();
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 2)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].nodeValue;
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 3)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[2].firstChild.nodeValue;
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 4)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[2].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[3].firstChild.nodeValue;
                            }*/
                            search = pobierzFraze(element, dlugosc);
                            document.getElementById("searchQueryBrowser").value = wycinanieFrazyProd(usunTagi(search));
                            obj_form2.submit();
                        }
                        else
                        {
                            /*if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 2)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].nodeValue;
                            }
                            else if (document.getElementById("suggestBoxField").childNodes[wybrany].childNodes.length == 3)
                            {
                                search = document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[0].nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[1].firstChild.nodeValue;
                                search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[2].nodeValue;
                            }*/
                            search = pobierzFraze(element, dlugosc);
                            search = usunTagi(wycinanieKluczaStrony(search));
                            window.location.href = tablicaLinkow [search.toLowerCase()];
                        }
    }
    document.getElementById("suggestBoxField").style.visibility = 'hidden';
}
function pobierzFraze(element, dlugosc)
{
    var search = '';
    for (i = 0; i < dlugosc; i++)
    {
        if (element.childNodes[i].nodeType == 3)
            search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[i].nodeValue;
        else
            search += document.getElementById("suggestBoxField").childNodes[wybrany].childNodes[i].firstChild.nodeValue;
    }
    return search;
}
function wstawTymczasowaPodpowiedz(wybrany)
{
    var search = document.getElementById("suggestBoxField").childNodes[wybrany].firstChild.nodeValue;
    document.getElementById("searchQueryBrowser").value = wycinanieFrazyProd(usunTagi(search));
}
function usunTagi(str)
{
    var tagREG=new RegExp('<[a-zA-Z/]{1,15}.*?>','g');
    return str.replace(tagREG,'');
}

