Ext.ns('Nexts.plugins');

/* config options
		id : [optional] Element id (or Element) of the resize target
  selector : [optional] CSS selector of the resize target (should not include an ID)
   onEvents : the containers event name(s) which defines when SizeTo is invoked
	  delay : [optional] milliseconds delay

   Example:	 plugins: [new Nexts.plugins.SizeToTarget({ onEvents:['render'], selector:'img.sizeToMe'}) ]
*/
Nexts.plugins.SizeToTarget = function(opt) {
	var options = Ext.apply({
		selector : null,
		onEvents : ['render'],
		delay	 : false,
		el		 : null
	},opt||{});

	return {
		init: function(c) {

			this.container = c;
			c.sizeToTarget = function(target) {

				var t = Ext.get(target) || arguments.callee.target , b;

				if(t && (b = this.body)){
					var tSize = t.getSize();

					//calc current offsets for body border and padding
					var bHeightAdj = b.getHeight() - b.getHeight(true);
					var bWidthAdj  = b.getWidth()  - b.getWidth(true);

					this.setSize(Math.max(this.minWidth || options.minWidth || 0, tSize.width  +  this.getFrameWidth() + bWidthAdj) ,
								 Math.max(this.minHeight || options.minHeight || 0, tSize.height +	this.getFrameHeight() + bHeightAdj) );

				}
			};
			//setup event listeners for resizing
			if(!!(options.onEvents||[]).length && (options.el || options.selector)){
				Ext.each([].concat(options.onEvents) ,
				   c.on.createDelegate(c,[this.hookTarget ,this,options.delay?{delay:options.delay}:null],1),
				this);

			}

		},
		hookTarget : function(){
			var o=options,
			   el = o.el,
			   s  = o.selector,
			   c = this.container;

			c.sizeToTarget.target = Ext.get(el) || c.body.child(s || el);
			c.sizeToTarget.call(c);

		}
	};
};

