if( typeof ShoppingCartItem == "undefined" )
	throw "Missing Class Dependency: ShoppingCartItem (shopping-cart-item.js)";

var ShoppingCart = Class.create(
{
	items: [],
	
	initialize: function()
	{
		this.initDOM();
		this.initOther();
		this.initEvents();
	},
	
	initDOM: function()
	{
		this.dom = {};
		this.dom.cartContents = $( "cart-contents" );
		this.dom.checkoutButton = $( "checkout" );
		this.dom.total = $( "cart-total" );
	},
	
	initOther: function()
	{
		var rows = this.dom.cartContents.getElementsByTagName( 'tr' );
		
		for( var i = 0; i < rows.length; i++ )
			if( $( rows[i] ).hasClassName( "item" ) )
				this.items.push( new ShoppingCartItem( this, rows[i] ) );
	},
	
	initEvents: function()
	{
		this.dom.checkoutButton.observe( "click", this.handleClickCheckout.bind( this ) );
	},
	
	removeItem: function( cart_item )
	{
		cart_item.destroy();
		delete this.items[ cart_item.getId() ];
	},
	
	setTotal: function( total )
	{
		this.dom.total.update( "$" + total );
	},
	
	// Event Handlers
	
	handleClickCheckout: function( e )
	{
		Event.stop( e );
		
		if( this.countItems() == 0 )
			return alert( "You cannot check out:\n\nYour cart is empty!" );
		
		window.location = this.dom.checkoutButton.getAttribute( "href" );
	},
	
	countItems: function()
	{
		var total = 0;
		
		for( var i = 0; i < this.items.length; i++ )
			total += this.items[i].getQuantity();
		
		return total;
	}
});

document.observe( "dom:loaded", function(){ new ShoppingCart() } );	