/*
Ajax AutoSuggest
===========
This file contains the functions which will do the autosuggest on client end
@version: 1.0
@author:  Waseem Khan
@blog:    http://blog.pakcoders.com
*/

/*

*/

var hidevar = 'yes'; //Used to stop suggestion list's onBlur event (disappearing) when a suggestion is clicked
var suggestFocused = "no"; //Used in clickButton function to know if a suggestion is focused or no
var idFocused = 0; //If suggestFocused = "yes" this variable shows the id of the focused suggestion

var ajaxObj = getAjaxObject();

var targetID = new Array() ;
var searchID = new Array() ;
var inputID = new Array() ;

var autoSugPointer = new Array(); //Used as a pointer to navigate through suggestions
var suggestions = new Array();

function autoSuggest(id, targetid, searchid, inputid, e)
{
	var keyCode = getKeyCode(e, 'keyup');
	if (keyCode == 40 || keyCode == 38 || keyCode == 13 ) {return false;}
   
	autoSugPointer[id] = 0;
   
	targetID[id] = targetid;
	searchID[id] = searchid;
	inputID[id] = inputid;
	countSuggestions[id] = 0;
			   
	var searchInput = getElemId(id).value;
		   
	var url = "autosuggest/autosearch.php"; //Path to php script executing the queries
	var params = "input=" + searchInput;
		   
	if (trim(searchInput) !== "") {sendRequest(ajaxObj, url, params, handleSuggestResponse, id);}
	else {hideSuggestions();}
}

function handleSuggestResponse(id)
{
	if (ajaxObj.readyState == 4)
	{
		if (ajaxObj.status == 200)
		{
			try
			{
				var XMLResponse = ajaxObj.responseXML.documentElement;
				// work with the xml response
			  
				var keywordsTag = XMLResponse.getElementsByTagName('keywords');
				var imagesTag = XMLResponse.getElementsByTagName('images');
				var linkTag = XMLResponse.getElementsByTagName('link');
			  
				suggestions.length = 0;
				var suggestimages = new Array();
				var suggestlink = new Array();
			  
				for (var i = 0; i < keywordsTag.length; i++)
				{
					var keywords = keywordsTag.item(i).firstChild.data.toString();
					suggestions.push(keywords);
					var images = imagesTag.item(i).firstChild.data.toString();
					suggestimages.push(images);
					var link = linkTag.item(i).firstChild.data.toString();
					suggestlink.push(link);
				}
				showSuggestions(suggestions, suggestimages, suggestlink, id);
			}
			catch(e)
			{
				hideSuggestions(id);
				if (trim(ajaxObj.responseText) !== "")
				alert(ajaxObj.responseText);
			}
		}
	}
}

var countSuggestions = new Array();
var linkarray = new Array() ;

function showSuggestions(suggestions, suggestimages, suggestlink, id)
{
	var listWrapID = getElemId(targetID[id]);
	listWrapID.style.visibility = "visible";
   
	var listID = getElemId(searchID[id]);
	listID.innerHTML = "";
      
	linkarray.length = 0;

	for(var i = 0; i < suggestions.length; i++)
	{
		listID.innerHTML += "<li><a id='"+id+"-" +(i+1)+"' href='"+suggestlink[i]+"' "+
		"onMouseOver=\"hidevar='no'; keyBoardNav('mouseover', this.id);\" "+
		"onMouseOut=\"hidevar='yes';suggestFocused = 'no';\">"+
		"<img src='"+suggestimages[i]+"'/>" +suggestions[i] + "</a><div class='clear'></div></li class='cleanup'><li>";   
		linkarray[i] = suggestlink[i] ; 
	}  
	countSuggestions[id] = i;
}


function clickButton(suggFoc,idFoc)
{
	if (suggFoc == "yes")
	{
		alink = linkarray[autoSugPointer[idFoc] - 1];
		alink = alink.replace("&amp;", "&");
		window.location = alink ;
	}
	else if (suggFoc == "no")
	{
		alink = "?page=search&text="+document.getElementById('input1').value;	
		window.location = alink ; 
	}
}

function keyBoardNav(e, id)
{
	if (e == "mouseover") //We get the id and give focus or blur on mouseover, rather than just using the ccs mouseover attribute
	{
		splid = id.split('-');
		for (var i=1;i<=suggestions.length;i++)
		{ revertAutoSuggestKeyNav(i, splid[0]);	}
		autoSugPointer[splid[0]] = splid[1];
		changeAutoSuggestKeyNav(autoSugPointer[splid[0]], splid[0]);
	}	
	else
	{
		var keyCode = getKeyCode(e, 'keydown');
	  
		if (keyCode == 40) //Hit DownArrow
		{
			if (autoSugPointer[id] >= 0 && autoSugPointer[id] < countSuggestions[id])
			{
				if (autoSugPointer[id] != 0 && autoSugPointer[id] != countSuggestions[id])
				{revertAutoSuggestKeyNav(autoSugPointer[id], id);}
				autoSugPointer[id] ++;
				changeAutoSuggestKeyNav(autoSugPointer[id], id);
		
				if (autoSugPointer[id] > 6)
				{getElemId(searchID[id]).scrollTop = 30;}
			}
			else if (autoSugPointer[id] >= 0 && autoSugPointer[id] == countSuggestions[id]) //When reaching the autosuggestion bottom go to the top again
			{
				revertAutoSuggestKeyNav(autoSugPointer[id], id);
				autoSugPointer[id] = 0;
			}
		}
		else if (keyCode == 38) //Hit UpArrow
		{
			if (autoSugPointer[id] > 1)
			{
				revertAutoSuggestKeyNav(autoSugPointer[id], id);
				autoSugPointer[id] --;
				changeAutoSuggestKeyNav(autoSugPointer[id], id);
				if (autoSugPointer[id] <= 2)
				{getElemId(searchID[id]).scrollTop = 0;}
			}
			else if (autoSugPointer[id] == 1) //When reaching the autosuggestion top go to the input field again
			{
				revertAutoSuggestKeyNav(autoSugPointer[id], id);
				autoSugPointer[id] = 0;
			}
			else if (autoSugPointer[id] == 0) //When begining from the input field go to the bottom
			{
				autoSugPointer[id] = 4;
				changeAutoSuggestKeyNav(autoSugPointer[id], id);
			}
		}
		else if (autoSugPointer[id] > 0 && keyCode == 13) //Hit Enter , autosuggest chosen
		{
			var alink = 0; 
			alink = linkarray[autoSugPointer[id] - 1];
			alink = alink.replace("&amp;", "&");
			window.location = alink ;
		}
		else if (autoSugPointer[id] == 0 && keyCode == 13) //Hit Enter, no autosuggest chosen
		{
			var alink = 0; 
			alink = "?page=search&text="+document.getElementById('input1').value;	
			window.location = alink ; 
		} 
	}	
}

function changeAutoSuggestKeyNav(id, ID) //Give focus to a suggestion
{
	idFocused = id;
	suggestFocused = "yes";
	getElemId(ID + "-" + id).style.backgroundColor = "#ddd";
	getElemId(ID + "-" + id).style.color = "#FFF";   	
}

function revertAutoSuggestKeyNav(id, ID) //Take away focus from a suggestion
{
	suggestFocused = "no";
	if (typeof getElemId(ID + "-" + id).style != "undefined")
	{
		getElemId(ID + "-" + id).style.backgroundColor = "#F9F9F9";
		getElemId(ID + "-" + id).style.color = "#006";  
	}
}

function hideSuggestions(id)
{
	if ( hidevar == 'yes' || hidevar == '')
	{
		try
		{
			var listWrapID = getElemId(targetID[id]);
			listWrapID.style.visibility = "hidden";	
		}
		catch(e){}
	}
}
