
var authorList = new Array();
var authorListIndex = new Array();

function authorObject(surname, forename, id)
{
	this.surname = surname;
	this.forename = forename;
	this.id = id;
}

function FetchAuthorList()
{
	new Ajax.Request('ajax/authorList.php',
					 {
						onException: ListRequestException,
						onSuccess: ListRequestSuccess,
						onFailure: ListRequestFailure,
						onComplete: ListRequestComplete
					 });
					 
		
}

function ListRequestSuccess(authorListResponse)
{
	var authorResults = authorListResponse.responseXML.getElementsByTagName('author');
	var currentSurname = '';
	var currentForename = '';
	var currentIndexLetter = '';
	var lastIndexLetter = ' ';
	
	if (authorResults != null && authorResults.length > 0)
	{
		for (i = 0; i < authorResults.length; i++)
		{
			currentSurname = authorResults[i].getElementsByTagName('surname')[0].childNodes[0].nodeValue;
			currentForename = authorResults[i].getElementsByTagName('forename')[0].childNodes[0].nodeValue;
		
			authorList.push(new authorObject(
											 currentSurname,
											 currentForename,
											 authorResults[i].getAttribute('authorId')
											)
							);
			
			currentIndexLetter = currentSurname.toUpperCase()[0];
			
			if (currentIndexLetter != lastIndexLetter)
				authorListIndex[currentIndexLetter] = i;
			
			lastIndexLetter = currentIndexLetter;
		}
	}
	
	if ($('searchAuthor').value != '')
		RefreshAuthorList($('searchAuthor').value);
}

function ListRequestException(request, exception)
{
	//alert(exception);
}

function ListRequestFailure(authorListResponse)
{
	//alert('failed');
}

function ListRequestComplete()
{
	
}

function FocusAuthorSearch(requestString)
{
	if (authorList.length <= 0)
		FetchAuthorList();
		
	if (requestString != '')
		$('authorListContainer').style.display = 'block';
	else
		$('authorListContainer').style.display = 'none';
}

function BlurAuthorSearch()
{
	$('authorListContainer').style.display = 'none';
}

function RefreshAuthorList(requestString)
{
	if (authorList.length <= 0)
		return;

	var authorListContainer = $('authorListContainer');
	
	if (requestString == '')
	{
		authorListContainer.style.display = 'none';
		return;
	}
	
	var authorListElement = $('authorList');

	authorListElement.innerHTML = '';
	
	var index = authorListIndex[requestString.toUpperCase()[0]];
	var inArea = false;
	var hits = 0;
	
	for (i = index; i < authorList.length; i++)
	{
		if (authorList[i].surname.substring(0, requestString.length).toLowerCase() == requestString.toLowerCase())
		{
			if (!inArea)
				inArea = true;
		
			authorListElement.innerHTML += '<li><a href="index.php?searchAuthor=' + authorList[i].id + '&act=viewCat">'
										+ authorList[i].surname + ', ' + authorList[i].forename + '</a></li>';
			++hits;
		}
		else
		{
			if (inArea)
				break;
		}
	}
	
	if (hits <= 0)
		authorListElement.innerHTML = '<li style="color: red;"> --- Kein Autor gefunden</li>';
		
	
	authorListContainer.style.display = 'block';
}