var _blog = window.IPBoard;

_blog.prototype.livec = {
	
	initialize: function(id, options)
	{
		Debug.write("Initializing ips.livecirculars.js");

			this.id = $( id ).id;
			this.timer = null;
			this.last_string = '';
			this.internal_cache = $H();
			this.pointer = 0;
			this.items = $A();
			this.observing = true;
			this.objHasFocus = null;
			this.options = Object.extend({
				min_chars: 3,
				classname: 'ipb_autocomplete'
			}, arguments[1] || {});
			
			//-----------------------------------------
			
			if( !$( this.id ) ){
				Debug.error("Invalid textbox ID");
				return false;
			}

			this.obj = $( this.id );
			
			if( !this.options.url )
			{
				Debug.error("No URL specified for autocomplete");
				return false;
			}
			
			$( this.obj ).writeAttribute('autocomplete', 'off');
			
			this.buildList();
			
			// Observe keypress
			$( this.obj ).observe('focus', this.timerEventFocus.bindAsEventListener( this ) );
			$( this.obj ).observe('blur', this.timerEventBlur.bindAsEventListener( this ) );

	},
	

	// Ze goggles are blurry!
	timerEventBlur: function(e)
	{
		window.clearTimeout( this.timer );
		this.eventBlur.bind(this).delay( 0.6, e );
	},
	
	// Phew, ze goggles are focussed again
	timerEventFocus: function(e)
	{
		this.timer = this.eventFocus.bind(this).delay(0.4, e);
	},
	
	eventBlur: function(e)
	{
		this.objHasFocus = false;
		
		if( $( this.list ).visible() )
		{
			var effect = new Effect.Fade( $(this.list), { duration: 0.3 } );
		}
	},
	
	eventFocus: function(e)
	{
		Debug.write("event focus called");
		if( !this.observing ){ return; }
		this.objHasFocus = true;
		
		// Keep loop going
		this.timer = this.eventFocus.bind(this).delay(0.6, e);

		var curValue = this.getCurrentName();

		if( curValue == this.last_string ){ return; }
		
		if( curValue.length < 3 || parseInt(curValue) < 100 ){
			// Hide list if necessary
			if( $( this.list ).visible() )
			{
				var effect = new Effect.Fade( $( this.list ), { duration: 0.3, afterFinish: function(){ $( this.list ).update() }.bind(this) } );
			}
			
			return;
		}

		this.last_string = curValue;
		
		// Cached?
		json = this.cacheRead( curValue );
		
		if( json == false ){
			// No results yet, get them
			var request = new Ajax.Request( this.options.url + '/ipb/1/keyword/' + escape( curValue ),
								{
									method: 'get',
									evalJSON: 'force',
									onSuccess: function(t)
									{
										this.updateAndShow( t.responseText );
									}.bind( this )
								}
							);
		}
		else
		{
			this.updateAndShow( json );
		}				
		
		//Debug.write( curValue );
	},
	
	updateAndShow: function( json )
	{
		if( !json ){ return; }
		
		this.updateList( json );

		if( !$( this.list ).visible() && this.objHasFocus )
		{
			Debug.write("Showing");
			var effect = new Effect.Appear( $( this.list ), { duration: 0.3 } );
		}
	},
	
	cacheRead: function( value )
	{
		if( !Object.isUndefined( this.internal_cache[ value ] ) ){
			Debug.write("Read from internal cache");
			return this.internal_cache[ value ];
		}
		
		return false;
	},
	
	cacheWrite: function( key, value )
	{
		this.internal_cache[ key ] = value;
		
		return true;
	},
	
	getCurrentName: function()
	{
		return $F( this.obj ).strip();
	},
	
	buildList: function()
	{
		if( $( this.id + '_ac' ) )
		{
			return;
		}
		
		var ac = new Element('div', { id: this.id + '_ac' } ).hide().addClassName('live_search');

		$('ipboard_body').insert({bottom: ac});

		var finalPos = {};
		
		// Position menu to keep it on screen
		var sourcePos = $( this.id ).viewportOffset();
		var sourceDim = $( this.id ).getDimensions();
		
		var delta = [0,0];
		var parent = null;
		var screenScroll = document.viewport.getScrollOffsets();
		
		if (Element.getStyle( $( this.id ), 'position') == 'absolute')
		{
			parent = element.getOffsetParent();
			delta = parent.viewportOffset();
	    }
	
		finalPos['left'] = sourcePos[0] - delta[0] - 330;
		finalPos['top'] = sourcePos[1] - delta[1] + screenScroll.top + 20;
		
		// Now try and keep it on screen
		finalPos['top'] = finalPos['top'];
		
		$( this.id + '_ac' ).setStyle('position: absolute; top: ' + ( finalPos['top'] ) + 'px; left: ' + ( finalPos['left'] ) + 'px;').hide();
		
		
		this.list = $( this.id + '_ac' );
	},
	
	updateList: function( json )
	{
		if( !json || !$( this.list ) ){ return; }
	

		
		$( this.list ).update( json );

	}
				
};
document.observe("dom:loaded", function(){
ipb.livec.initialize('inp-live-search', { url: livesearchUrl } );
});