var AjaxCart = Class.create(
{
	initialize: function(cartPath, checkoutPath, alertContainer, numItems)
	{
		this.cartPath = cartPath;
		this.checkoutPath = checkoutPath;
		this.forms = $$('form.ajaxItem');
		this.alertContainer = alertContainer;
		this.numItems = numItems;
		this.start();
	},
	
	start: function()
	{
		this.forms.each(function(form)
		{			
			form.observe('submit', this.sendRequest.bind(this));
		}.bind(this));
	},
	
	sendRequest: function(event)
	{
		event.stop();
		
		this.form = event.element();
		
		new Ajax.Request(this.cartPath + '?mode=add', 
		{
			parameters: this.form.serialize() + '&ajaxRequest=true', 
			onSuccess: this.processAjax.bind(this)
		});
	},
	
	processAjax: function(transport)
	{
		var data;
		
		try {
			data = transport.responseText.evalJSON();
		}
		catch(err)
		{}
		
		if (data)
		{	
			this.doSuccess(data);
		}
		else
		{
			window.location = this.cartPath;
		}
	},

	doSuccess: function(data)
	{
		var num;
		
		if (num = data.cartNumberOfItems)
		{
			$(this.numItems).update(num);
		}
		
		this.buildAlertContainer();
	},
	
	buildAlertContainer: function()
	{
		this.alertContainer = $(this.alertContainer).addClassName(this.alertContainer).update('').setOpacity(0);
		
		var closeButton = new Element('a', {className: 'close', href: '#'}).observe('click', this.closeAlertContainer.bind(this));
		var checkoutButton = new Element('a', {className: 'checkout', href: this.checkoutPath});
		var continueButton = new Element('a', {className: 'continue', href: '#'}).observe('click', this.closeAlertContainer.bind(this));
		
		this.alertContainer.appendChild(closeButton);
		
		var buttonsContainer = new Element('div', {className: 'buttonsContainer'});
		
		buttonsContainer.appendChild(checkoutButton);
		buttonsContainer.appendChild(continueButton);
		
		this.alertContainer.appendChild(buttonsContainer);
		
		Effect.ScrollTo(document.body, {duration: 0.4});
		Effect.Appear(this.alertContainer, {duration: 0.4});
	},
	
	closeAlertContainer: function()
	{
		this.alertContainer.hide();
	}
});

