Ext.ns('Ext.ux');

Ext.ux.ScrollFixedBox = Ext.extend(Ext.util.Observable, {

	padding: 10
	,boundingContainer: false
	,bottomStop: false

	,constructor: function(containerId, config) {

        config = config || {};
        Ext.apply(this, config);

		this.containerEl = Ext.get(containerId);
		this.containerHeight = this.containerEl.getHeight();
		this.initialTop = this.containerEl.getTop();
		
		if(this.boundingContainer)
		{
			this.boundingContainer = Ext.get(this.boundingContainer);
			this.bottomStop = this.boundingContainer.getBottom() - this.containerHeight - this.padding;
		}
		
		if(this.bottomStop)
		{
			this.maxMargin = this.bottomStop - this.initialTop
		}
		
		
		Ext.fly(window).on("scroll", this.handleScroll, this);
		Ext.fly(window).on("load", this.handleScroll, this, {delay: 100});
		
	}

	,handleScroll: function (){
		
		var containerTop = this.containerEl.getTop();
		
		if(containerTop-this.padding < window.pageYOffset)
		{
			if(!this.boundingContainer || window.pageYOffset+this.containerHeight < this.boundingContainer.getBottom())
			{
				// push floater down
				//console.log("down scroll to %s", window.pageYOffset);
				this.containerEl.animate({'margin-top': {to: window.pageYOffset-this.initialTop+this.padding}});
			}
			else if(this.bottomStop && window.pageYOffset > this.bottomStop)
			{
				// push floater to bottom
				//console.log("bottom scroll to %s , max: %s", window.pageYOffset, this.maxMargin);
				this.containerEl.animate({'margin-top': {to: this.maxMargin}});
			}
		}
		else if(containerTop-this.padding > window.pageYOffset)
		{
			if(window.pageYOffset > this.initialTop)
			{
				// pull floater up
				//console.log("up scroll to %s", window.pageYOffset);
				this.containerEl.animate({'margin-top': {to: window.pageYOffset-this.initialTop+this.padding}});
			}
			else if (containerTop != this.initialTop)
			{
				// set floater to starting point
				//console.log("0 scroll to %s", window.pageYOffset);
				this.containerEl.animate({'margin-top': {to:0}});
			}
		}
		
		/* use position: fixed?
		if(containerTop < window.pageYOffset)
		{
			this.containerEl.setStyle({
				position: 'fixed'
				,top: this.initialTop
				,left: this.containerEl.getLeft()
			});	
		}
		else if(containerTop > window.pageYOffset)
		{
			//this.containerEl.setStyle('position', 'relative');	
		}
		*/
	}
	
});
