
var ShoppingCartLink = Class.create(
{
	uri: "/cart/simplejson",
	
	data: {},
	
	initialize: function( element )
	{
		this.element = $( element );
		this.initDOM();
		this.initEvents();
	},
	
	initDOM: function()
	{
		this.dom = {};
		this.dom.items = $( "cart-link-items" );
		this.dom.total = $( "cart-link-total" );
	},
	
	initEvents: function()
	{
		Event.observe( document, "cart:change", this.handleCartChange.bind( this ) );
	},
	
	handleCartChange: function( e )
	{
		this.refresh();
	},
	
	refresh: function()
	{
		new Ajax.Request( this.uri,
		{
			method: "get",
			onSuccess: this.update.bind( this )
		});
	},
	
	update: function( transport )
	{
		this.data = transport.headerJSON;

		if( this.data.has_cart == false )
			return;
		
		//Effect.Pulsate( this.element, { pulses: 1, duration: 0.33 } );
		
		new Effect.Opacity( this.element,
		{
			duration: 0.2,
			from: 1.0,
			to: 0.0,
			afterFinish: function()
			{
				this.setItemCount( this.data.item_count );
				this.setTotal( this.data.total );
				new Effect.Opacity( this.element,
				{
					duration: 0.2,
					from: 0.0,
					to: 1.0
				});
			}.bind( this )
		});
	},
	
	setItemCount: function( count )
	{
		this.dom.items.update( count + " items" );
	},
	
	setTotal: function( total )
	{
		this.dom.total.update( total );
	}
});

document.observe( "dom:loaded", function(){ new ShoppingCartLink( "shopping-cart-link" ) } );