function AutoSuggest( url, inputFieldId, suggestionBoxId )
{
	// Initialize vars
	this.url = url;
	this.selectedIndex = 0;
	this.suggestionsEnabled = false;
	this.inputFieldId = inputFieldId;
	this.suggestionBoxId = suggestionBoxId;
	this.off = false;
}

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 = $( this.inputFieldId ).val();
	this.enableSuggestions( trim( inputValue )  != '' );

	if( this.suggestionsEnabled )
	{
		if( keyCode == 37 || keyCode == 39 || keyCode > 90 || ( keyCode < 65 && keyCode != 38 && keyCode != 40 && keyCode != 13 && keyCode != 27 && keyCode != 8 ) )
			return true;

		// Do something with selection?
		if( keyCode == 38 )
                {
                    if ( this.selectedIndex > 1 )
		    {
			this.unsetSelected();
			this.selectedIndex--;   //arrow up
			this.setSelected();
		    }
		    return true;
                }
		else if( keyCode == 40 )
                {
		    if( $("#autosuggest_" + (this.selectedIndex + 1)).length )
		    {
			this.unsetSelected();
			this.selectedIndex++;   //arrow down
			this.setSelected();
		    }
		    return true;
                }
		else if( keyCode == 13 )
		{
                        //enter 
			if( this.selectedIndex == 0 )
			{
			  this.enableSuggestions( false );
			  return true;
			}
			else
			{
			  selected = $("#autosuggest_" + this.selectedIndex).html();
			  selected = selected.replace('<b>', '')
			  selected = selected.replace('</b>', '')
			  selected = selected.replace('<B>', '')
			  selected = selected.replace('</B>', '')
			  updateLocationField( selected );
			  this.enableSuggestions( false );
			  return false;
			}
		}
		else if( keyCode == 27 )
		{
			this.enableSuggestions( false );
			this.off = true;
			return false; 
		}

		this.selectedIndex = 0;

		// Create vars to make these visible to the Ajax.Request method.
		var suggestionBox = $( this.suggestionBoxId );

		// Update content
		new $.ajax({
                    url: this.url + "?input=" + encodeURIComponent( inputValue ) + "&validate=",
                    cache: false,
                    success: function( transport )
                    {
                    	var response = trim( transport ) || "";
						if( response != '' )
						{
							suggestionBox.html( response );
                           
							//IE fix: show iframe
							var ieFrame = $( '#autosuggestIEfix' );
							if( ieFrame )
							{
								var offset = suggestionBox.offset();
								ieFrame.css('display', 'block');
								ieFrame.css('top', offset.top);
								ieFrame.css('left', offset.left);
								ieFrame.css('height', offset.height);
								ieFrame.css('width', offset.width);
                            }
						}
					}
		});
	}
}

AutoSuggest.prototype.setSelected = function(  )
{
	$("#autosuggest_" + this.selectedIndex).addClass('active');
}

AutoSuggest.prototype.unsetSelected = function(  )
{
	$("#autosuggest_" + this.selectedIndex).removeClass('active');
}

// Is the input correct? If so, return true, else false.
AutoSuggest.prototype.validateInput = function( errorNotificatorId, errDisplay )
{
	success = true;
	var inputField = $( this.inputFieldId );
	var errorNotificator = $( errorNotificatorId );

	if( trim( inputField.val() ) == '' )
		return true;    

	new $.ajax({
			url: this.url + "?input=" + encodeURIComponent( inputField.val() ) + "&validate=true",
            cache: false,
            async: false,
            success: function( transport )
            {
	        	var response = trim( transport ) || "";
	        	if( response != "" )
				{
					errorNotificator.css( 'display', 'none' );
				}
				else
				{
					errorNotificator.html( '<strong>' + inputField.val() + '</strong> ' + gettext('could not be found.') );
					errorNotificator.css( 'display', errDisplay );
					success = false;
				}
			}
    })

	return success;
}

// Enable or disable the suggestions
AutoSuggest.prototype.enableSuggestions = function( enable )
{
	if( !this.off )
	{
		if ( !enable ) {
		    this.unsetSelected();
		    this.selectedIndex = 0;

		    $( this.suggestionBoxId ).html( '' );
		    $( this.suggestionBoxId ).css('display', 'none');
		    
		    // IE Fix: remove Iframe
		    var ieFrame = $( '#autosuggestIEfix' );
		    if( ieFrame )
		    {
				ieFrame.css('display', 'none');
		    }
	
		} else {
		    $( this.suggestionBoxId ).css('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 place field on click
function updateLocationField( name )
{
    $( '#id_l' ).val(name);
}
