(function(){

/*
	Class: Container 
	The base data object for a Container 
*/
function Container() 
{ 
	this.box_list = new window['SB']['util']['List'];
	
	SButil.EventManager.addListener("BoxDeleted", onBoxDeleted, this);
	//SButil.EventManager.addListener("BoxAdded", onBoxAdded, this);
}

Container.prototype.toString = function() { return "[SB.core.Container]"; };

//Group: Basic Methods 
/*
	Function: setConfig
	Establishes the basic setup for the Container.
	
	inConfig - A configuration array (key/value)

	Configuration Array Options:
	name - The name of the Container 
*/
Container.prototype.setConfig = function( inConfig )
{
	if( inConfig.name )
		this.name = inConfig.name;

	if( inConfig.pallet_id )
		this.id = this.container_id = inConfig.pallet_id;

	if( inConfig.id )
		this.container_id = inConfig.id;

	if( inConfig.parent_id )
		this.parent_id = inConfig.parent_id;

	if( inConfig.children )
	{
		var el = 0;
		
		for( el in inConfig.children )
		{
			if( inConfig.children[el].crate_id )
			{
				var box = new SBCore.Box();
				box.setConfig( inConfig.children[el] );
				this.addBox( box );
			}
		}
		
	}
	

};

/*
	Function: addBox
	A method for associating a box to the container. A Box can only be inside of one container, so the previous "owner" is removed. 

	inBox - The box to add to the container
*/
Container.prototype.addBox = function( inBox ) 
{
	if( inBox.container ) 
		inBox.container.removeBox( inBox );

	this.box_list.append( inBox );	
	inBox.setParent( this );
};

/*
	Function: removeBox
	A method for removing the association for a box to the container.

	inBox - The box to add to the container
*/
Container.prototype.removeBox = function( inBox ) 
{
	//this.box_list.remove( inBox );	
	//inBox.box_obj.setParent( null );
	
	this.box_list.remove( inBox );	
	inBox.setParent( null );

};

/*
*	Function trash 
*	Calls back to the server to remove the container object, if successful
*	an event is broadcast
*/
Container.prototype.trash = function()
{
	var url = "/container/remove";
	var callback = { success:onDeleteSuccess,
			 timeout:5000,
			 arguments: { id:this.id, obj:this} };
	YUIRequest.asyncRequest( 'POST', url, callback, "id="+this.id );		
};

//Delete callbacks
function onDeleteSuccess( inReq )
{
	var container = this.arguments.obj;
	param = { container_id:this.arguments.id };
	SButil.EventManager.fireEvent( "ContainerDeleted", param );



	delete container;
}

function onBoxDeleted(inEvent, inArgs )
{
	if( inArgs[0].container.id == this.id )
		this.removeBox(inArgs[0].box.box_obj);
}

function onBoxAdded(inEvent, inArgs )
{
	var newBox = new SBCore.Box();
	var inConfig = { name:inArgs[0].name,
					 crate_id:inArgs[0].box_id,
				     pallet_id:inArgs[0].container.container_id
				    }
	
	newBox.setConfig( inConfig );
	inArgs[0].container.addBox(newBox);
	
	SButil.EventManager.fireEvent( "BoxAddedView", inArgs[0] );

}

	
	
window['SB']['core']['Container'] = Container;

})();
