// Constructs a new AutoSuggest. url Is the url to the result page to include. The inputFieldId is the id of the input element. suggestionBoxId is the id of the div-element which contains the suggestions.
// If there are multiple autosuggests at the same page and with the same include file, you should set the number parameter to a unique value for the autosuggests on the page. function updatePlaceField( name ) should then be function updatePlaceField2( name ) for the autosuggest with number 2.
function AutoSuggest( url, inputFieldId, suggestionBoxId, number )
{
	// Initialize vars
	this.url = url;
	this.selectedIndex = 0;
	this.suggestionsEnabled = false;
	this.inputFieldId = inputFieldId;
	this.suggestionBoxId = suggestionBoxId;
	if( number == undefined )
	{
		this.number = -1;
	}
	else 
	{
		this.number = number;
	}
}

AutoSuggest.prototype.checkEnter = function( keyCode )
{
  if( keyCode == 13 )
  {
    if( this.suggestionsEnabled )
    {
      return this.updateSuggestions( keyCode );
    }
    else
    {
      return true;
    }
  }
}

// Update the list of suggestions
AutoSuggest.prototype.updateSuggestions = function( keyCode )
{
	var	inputValue = document.getElementById( this.inputFieldId ).value;

	this.enableSuggestions( trim( inputValue )  != '' );

	if( this.suggestionsEnabled )
	{
		// Do something with selection?
		if( keyCode == 38 )
		{
			//arrow up
			this.selectedIndex--;
		}
		else if( keyCode == 40 )
		{
			//arrow down
			this.selectedIndex++;
		}
		else if( keyCode == 13 )
		{
			//enter
      if( this.selectedIndex == 0 )
      {
        this.setSelected();
        this.enableSuggestions( false );
        return true;
      }
      else
      {
        this.setSelected();
        this.enableSuggestions( false );
        return false;
      }
		}

		// Create vars to make these visible to the Ajax.Request method.
		var suggestionBox = document.getElementById( this.suggestionBoxId );

		// Update content
		new Ajax.Request( '/' + this.url + '&input=' + inputValue + '&selectedIndex=' + this.selectedIndex + '&number=' + this.number,
			{
				method:'get',
				asynchronous: true,
				onSuccess: function( transport )
				{
					var response = trim( transport.responseText ) || "";
					if( response != '' )
					{
						suggestionBox.innerHTML = response;

            //IE fix: show iframe
            var ieFrame = $( 'autosuggestIEfix' );
            if( ieFrame )
            {
              ieFrame.style.display = 'block';
              ieFrame.style.top = suggestionBox.offsetTop;
              ieFrame.style.left = suggestionBox.offsetLeft;
              ieFrame.style.height = suggestionBox.offsetHeight;
              ieFrame.style.width = suggestionBox.offsetWidth;
            }
					}
				}
			}
		);
	}
}

// When a suggestion is selected, the user presses enter. Set the text value to the selected value.
AutoSuggest.prototype.setSelected = function(  )
{
	// Create vars to make these visible to the Ajax.Request method.
	var inputField = document.getElementById( this.inputFieldId );
	var inputFieldNameUrl = document.getElementById( this.inputFieldId + 'NameUrl' );

	new Ajax.Request( '/' + this.url + '&input=' + encodeURIComponent( inputField.value ) + '&selectedIndex=' + this.selectedIndex + '&return=true&number=' + this.number,
		{
			method:'get',
			onSuccess: function( transport )
			{
				var response = trim( transport.responseText ) || "";
				if( response != "" )
				{
					inputField.value = response;
					inputField.focus();
					return true;
				}
			}
		}
	);
	return false;
}

// Is the input correct? If so, return true, else false.
AutoSuggest.prototype.validateInput = function( errorNotificatorId, errDisplay )
{
	var success = true;
	var inputField = document.getElementById( this.inputFieldId );
	var errorNotificator = document.getElementById( errorNotificatorId );

	if( trim( inputField.value ) == '' || inputField.value == inputField.defaultValue )
	{
		return true;
	}
	
	new Ajax.Request( '/' + this.url + '&input=' + encodeURIComponent( inputField.value ) + '&validate=true&number=' + this.number,
		{
			method:'get',
			asynchronous: false,
			onSuccess: function( transport )
			{
				var response = trim( transport.responseText ) || "";
				if( response.length > 0 )
				{
						errorNotificator.style.display = 'none';
				}
				else
				{
					// Make clear the input is incorrect.
					errorNotificator.innerHTML = '<strong>' + inputField.value + '</strong> kon niet worden gevonden.';
					errorNotificator.style.display = errDisplay;
					success = false;
				}
			}
		}
	);
	return success;
}

// Get nameUrl
AutoSuggest.prototype.getNameUrl = function()
{
	var nameUrl = '';
	var inputField = document.getElementById( this.inputFieldId );
	
	new Ajax.Request( '/' + this.url + '&input=' + encodeURIComponent( inputField.value ) + '&validate=true&number=' + this.number,
		{
			method:'get',
			asynchronous: false,
			onSuccess: function( transport )
			{
				var response = trim( transport.responseText ) || "";
				if( response.length > 0 )
				{
						nameUrl = response;
				}
			}
		}
	);
	return nameUrl;
}

// Enable or disable the suggestions
AutoSuggest.prototype.enableSuggestions = function( enable )
{
	if( !enable )
	{
		this.selectedIndex = 0;
		document.getElementById( this.suggestionBoxId ).style.display = 'none';

    // IE Fix: remove Iframe
    var ieFrame = $( 'autosuggestIEfix' );
    if( ieFrame )
    {
      ieFrame.style.display = 'none';
    }
	}
	else 
	{
		document.getElementById( this.suggestionBoxId ).style.display = 'block';
	}
	this.suggestionsEnabled = enable;
}

// Is the box enabled?
AutoSuggest.prototype.isEnabled = function( )
{
	return this.suggestionsEnabled;
}

// Static trim function
// Caution: Also removes enters and tabs.
function trim( str )
{
	str = str.replace(/^\s+/, '');
	str = str.replace(/\s+$/, '');
	str = str.replace(/^\n+/, '');
	str = str.replace(/\n+$/, '');
	str = str.replace(/^\t+/, '');
	str = str.replace(/\t+$/, '');
	return str;
}

	// Update recruiter field on click
	function updateRecruiterField( name )
	{
		$( 'r' ).value = name;
	}
	
	// Update place field on click
	function updatePlaceField( name )
	{
		$( 'p' ).value = name;
	}
