function autocomplete (input, options, textVal)
{
	var textValue = textVal;
	
	//console.log ("autocomplete (" + input + ", " + options + ")");
	// Create a link to self
	var me = this;
	
	// Turnning off autocomplete
	if (input.autocomplete != "off") input.autocomplete = "off";

	// Apply inputClass if necessary
	if (options.inputClass) input.className = options.inputClass;

	// Create results
	var results = document.createElement("div");
	results.style.display = "none";
	results.className = options.resultsClass;
	if (options.width > 0) results.style.width = options.width;
	
	// Add to body element
	document.body.appendChild(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = 0;
	var cache = {};
	var keyb = false;
	var hasFocus = true;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache()
	{
		//console.log ("flushCache ()");
		cache = {};
		cache.data = {};
		cache.length = 0;
	}

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null )
	{
		var sFirstChar = "", stMatchSets = new Array (), row;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ )
		{
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 )
			{
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
				//console.log ("stMatchSets[sFirstChar] : " + stMatchSets[sFirstChar]);
				//console.log ("row : " + row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets )
		{
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}
	
	if(!Array.indexOf)
	{
		Array.prototype.indexOf = function(obj)
		{
			for(var i = 0; i < this.length; i++)
			{
				if(this[i] == obj)
				{
					return i;
				}
			}
			
			return -1;
		}
	}


	input.onkeydown = function(ev)
	{
		//console.log ("input.onkeydown (" + ev.keyCode + ")");
        flushCache();
        
        var e = ev || window.event;
		// track last key pressed
		lastKeyPressCode = e.keyCode? e.keyCode : e.charCode;
		
		switch(lastKeyPressCode)
		{
			case 38: 	// UP
				if(e.preventDefault)
				{
					e.preventDefault();
				}
				else
				{
					e.returnValue = false; // IE branch - do more tests if that's not enough
				}
				moveSelect(-1);
				break;
			
			case 40: 	// DOWN
				if(e.preventDefault)
				{
					e.preventDefault();
				}
				else
				{
					e.returnValue = false; // IE branch - do more tests if that's not enough
				}
				moveSelect(1);
				break;
			
			case 9:  // TAB
			case 13: // RETURN
				if( selectCurrent() )
				{
					// make sure to blur off the current field
					input.blur();
					if(e.preventDefault)
					{
						e.preventDefault();
					}
					else
					{
						e.returnValue = false; // IE branch - do more tests if that's not enough
					}
					
					document.searchform.onsubmit();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}

	input.onfocus = function()
	{
		//console.log ("input.onfocus ()");
		clearIt (input, textValue);
        flushCache();
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	}
	
	input.onblur = function()
	{
		//console.log ("input.onblur ()");
		isFilled(input, textValue);
        flushCache();
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	}

	hideResultsNow();

	function onChange()
	{
		//console.log ("onChange ()");
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) )
		{
			results.style.display = "none";
			return;
		}
		
		var v = input.value;
		if (v == prev) return;
		prev = v;
		
		if (v.length >= options.minChars)
		{
			input.className += " " + options.loadingClass;
			requestData(v);
		} 
		else
		{
			input.className = input.className.split (" ")[0];
			results.style.display = "none";
		}
		
	}

 	function moveSelect(step)
 	{
 		//console.log ("moveSelect (" + step + ")");
		var lis = getChildTags ("li", null, results.childNodes[0]);
		if (!lis) return;

		active += step;
		
		if (active < 0)
		{
			active = 0;
		}
		else if (active >= lis.length)
		{
			active = lis.length - 1;
		}

		for (var l in lis)
		{
			lis[l].className = "";
			
			if (l == active)
				lis[l].className = "ac_over";
		}

	}

	function selectCurrent()
	{
		//console.log ("selectCurrent ()");
        flushCache();
		var li = getChildTags ("li", "ac_over", results.childNodes[0])[0];
		if (!li)
		{
			var $li = getChildTags ("li", null, results.childNodes[0]);
			if (options.selectOnly)
			{
				if ($li.length == 1) li = $li[0];
			}
			else if (options.selectFirst)
			{
				li = $li[0];
			}
		}
		
		if (li)
		{
			selectItem(li);
			return true;
		}
		else
		{
			return false;
		}
	};
	
	function selectItem(li)
	{
		//console.log ("selectItem (" + li + ")");
        flushCache();
		if (!li)
		{
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = (li.selectValue ? li.selectValue : li.innerHTML).trim();
		input.lastSelected = v;
		prev = v;
		results.innerHTML = "";
		input.value = v;
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	function showResults()
	{
		//console.log ("showResults ()");
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : input.offsetWidth;
		// reposition
		results.style.width = (parseInt(iWidth)) + "px";
		results.style.top = (pos.y + input.offsetHeight) + "px";
		results.style.left = (pos.x) + "px";
		results.style.display = "block";
//		results.innerHTML = "<img src='/images/ajax-loader.gif' style='float:right' />";
	};

	function hideResults()
	{
		//console.log ("hideResults ()");
        flushCache();
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow()
	{
		//console.log ("hideResultsNow ()");
		if (timeout) clearTimeout(timeout);
		input.className = input.className.split (" ")[0];
		
		if (results.style.display = "block")
		{
			results.style.display = "none";
		}
		
		if (options.mustMatch)
		{
			var v = input.value;
			if (v != input.lastSelected)
			{
				selectItem(null);
			}
		}
	};

	function receiveData(q, data)
	{
		//console.log ("receiveData (" + q + ", " + data + ")");
		if (data) 
		{
			input.className = input.className.split (" ")[0];
			
			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if (navigator.appName === "Microsoft Internet Explorer")
			{
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				results.appendChild(document.createElement("iframe"));
			}
			
			results.innerHTML = "";
			
			results.appendChild(dataToDom(data));
			
			showResults();
		}
		else
		{
			hideResultsNow();
		}
	}

	function parseData(data)
	{
		//console.log ("parseData (" + data + ")");
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++)
		{
			var row = rows[i].trim();
			if (row)
			{
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data)
	{
		//console.log ("dataToDom (" + data + ")");
		var ul = document.createElement("ul");
		var num = data.length;
		
		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			var span1 = document.createElement("span");
			var span2 = document.createElement("span");
			
			var splt = row[0].split (";");
			
			span1.innerHTML = splt[0];
			span2.innerHTML = splt[1].substring (1, splt[1].length);
			
			span1.id = "span1";
			span1.className = "item_name";
			span2.className = "item_count";
			
//			if (options.formatItem) {
//				li.innerHTML = options.formatItem(row, i, num);
//				li.selectValue = row[0];
//			} else {
//				li.innerHTML = row[0];
//				li.selectValue = row[0];
//			}
			
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			
			li.appendChild(span1);
			li.appendChild(span2);
			
			li.selectValue = splt[0];
			
			ul.appendChild(li);
			li.onmouseover = function ()
			{
				//console.log ("li.onmouseover ()");
				lis = getChildTags ("li", null, ul);
				 
				for (tag in lis)
				{
					if (lis[tag] === this)
					{
						lis[tag].className = "ac_over";
					}
					else
					{
						lis[tag].className = "";
						active = lis.indexOf (li);
					}
				}
			};
			
			li.onmousedown = function (ev)
			{
				//console.log ("li.onmousedown ()");
				var e = ev || window.event;
				
				if( selectCurrent() )
				{
					// make sure to blur off the current field
					input.blur();
					if(e.preventDefault)
					{
						e.preventDefault();
					}
					else
					{
						e.returnValue = false; // IE branch - do more tests if that's not enough
					}
					
					document.searchform.onsubmit();
				}
			};
		}
		return ul;
	};

	function requestData(q)
	{
		//console.log ("requestData (" + q + ")");
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data)
		{
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		}
		else if( (typeof options.url == "string") && (options.url.length > 0) )
		{
			var xhr = createXMLHttpRequestObject();
			
			xhr.onreadystatechange = function ()
			{
		        if (xhr.readyState == 4)
		        {
		            if(xhr.status == 200)
		            {
		            	data = parseData(xhr.responseText);
						addToCache(q, data);
						receiveData(q, data);
		            }
		            else
		            {
		                console.log("loadAndEval: Load failed!");
		            }
		        }
		    };
		    
		    xhr.open("GET", makeUrl(q), true);
		    xhr.send(null);
		}
		else	// if there's been no data found, remove the loading class
		{
			var it = document.createElement ("i");
			it.innerHTML = "No suggestions";
			results.appendChild(it);
		}
	}

	function makeUrl(q)
	{
		//console.log ("makeUrl (" + q + ")");
		var url = options.url + "?q=" + encodeURI(q) ;
		for (var i in options.extraParams)
		{
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
        
		return url;
	};
	
	function loadFromCache(q)
	{
		//console.log ("loadFromCache (" + q + ")");
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset)
		{
			for (var i = q.length - 1; i >= options.minChars; i--)
			{
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c)
				{
					var csub = [];
					for (var j = 0; j < c.length; j++)
					{
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q))
						{
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub)
	{
		//console.log ("matchSubset (" + s + ", " + sub + ")");
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function()
	{
		flushCache();
	};
	
	function addToCache(q, data)
	{
		//console.log ("addToCache (" + q + ", " + data + ")");
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength)
		{
			flushCache();
			cache.length++;
		}
		else if (!cache[q])
		{
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj)
	{
		//console.log ("findPos (" + obj + ")");
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		var obj = new Object();
		obj.x = curleft;
		obj.y = curtop;
		return obj;
	}
	
	function getChildTags (tag, tagClass, ul)
	{
		//console.log ("getChildTags (" + tag + ", " + tagClass + ", " + ul + ")");
		var tags = Array ();
		var counter = 0;
		var children = ul.childNodes;
		
		for (var i = 0; i < children.length; i++)
		{
			var child = children[i];
			
			if (tagClass != null)
			{
				if (child.tagName.toLowerCase () == tag && child.className == tagClass)
				{
					//console.log ("tag & indexOf : " + child.innerHTML);
					tags[counter] = child;
					counter++;
				}
			}
			else if (child.tagName.toLowerCase() == tag)
			{
				tags[counter] = child;
				counter++;
			}
		}
		
		return tags;
	}
}

function autocompleteFunc (url, options, data, input, textFieldValue)
{
	//console.log ("autocompleteFunc (" + url + ", " + options + ", " + data + ")");
	options = options || {};
	options.url = url;
	options.data = ((data != null) && (typeof data == "object") && (data.constructor == Array)) ? data : null;

	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {lang : 'en'};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.width = parseInt(options.width, 10) || 0;

	new autocomplete(input, options, textFieldValue);
}

function autocompleteArray (data, options)
{
	console.log ("autocompleteArray (" + data + ", " + options + ")");
	return this.autocomplete(null, options, data);
}

function indexOf (e)
{
	console.log ("indexOf (" + e + ")");
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};

function findValue(li)
{
	console.log ("findValue (" + li + ")");
	if( li == null ) return alert("No match!");

	if( !!li.extra ) var sValue = li.extra[0];

	else var sValue = li.selectValue;
}

function selectItem(li)
{
	console.log ("selectItem (" + li + ")");
	findValue(li);
}

function lookup()
{
	console.log ("lookup ()");
    var oSuggest = document.getElementById("searchbox")[0].autocompleter;

	oSuggest.findValue();
    
    return false;
}

function langParam()
{
    var location = window.location.href;
    var lang = "";
    var split = location.split("/");
    
    if (split.length > 3)
    {
    	lang = location.split ("/")[3];
    }
    else
    {
    	lang = "en";
    }
    
    return lang;
}

//creates an XMLHttpRequest instance
function createXMLHttpRequestObject()
{
  // xmlHttp will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // try to instantiate the native XMLHttpRequest object
  try
  {
    // create an XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    catch(e) { }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

function onLoadFunc (textFieldValue)
{
	var input = document.getElementById ("searchbox");
	var params = new Object ();
	params.delay = 1;
	params.minChars = 1;
    params.maxItemsToShow = 10;
    params.cacheLength = 0;
    params.inputClass = "searchbar";
    
    var l = langParam();
    
    if (l == "" || l == "pt" || l == "pl" || l == "se" || l == "tr" || l == "cz" || l == "sk" || l == "no" || l == "fi" || l == "dk" || l == "hu")
    	l = "en";
    
    var extra = new Object ();
    extra.lang = l;
    params.extraParams = extra;

    autocompleteFunc ("/MasterServlet", params, null, input, textFieldValue);
//    randomize_link_cloud ();
}

String.prototype.trim = function()
{ 
	return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function change_menu (item)
{
    var location = window.location.href;
    var lang = langParam();
    
    if (lang != "")
    {
        url = location.replace ("/" + lang, "/" + item.id);
    }
    else
    {
        url = location + item.id;
    }
    
    window.location = url;
}

function bodyClicked ()
{
    document.getElementById("searchbox").innerHTML = "";
}

function clearIt (searchBox, text)
{	
    if (searchBox.value == text)
    {
        searchBox.value = "";
        searchBox.style.color = "black";
    }
}

function isFilled(searchBox, whatToWrite)
{
    if (searchBox.value == "")
    {
        searchBox.value = whatToWrite;
        searchBox.style.color = "#AAAAAA";
    }
}
//promenio sam i ovde
function submitWhat (lang, field, direction)
{
    var loc = window.location.href;
    var changed = document.getElementById (field).value.replace(/ /g, ";");
    
    var url = "";
	
    if (loc.indexOf ("/" + lang) == -1)
    {
        url = loc + lang;
    }
    else
    {
        url = loc.substring (0, loc.indexOf ("/" + lang) + 3);
    }
	
    if (loc.indexOf ("/visual-search") != -1)
    {
    	url += "/visual-search";
    }
    else
    {
    	url +=  "/" + direction;
    }
    
    url +=  "/what-" + changed + "/page-1";
	
	
    window.location = url;
	
    return false;
}

function item_click (item)
{
	var url = item.href;
	item.href = url.replace(/#/, "/");
}

/* funkcije za meni za izbor jezika */
function makeTall(){ 
    document.getElementById('languages').style.height = '295px'; document.getElementById('languages').style.border = '1px solid #3366CC';
}
function makeShort(){ 
    document.getElementById('languages').style.height = '18px'; document.getElementById('languages').style.border = 'none';
}