var cart = new Class( {
	
	addToCart: function( id, colour, qty, price ) {
		new Ajax( 'ajax.php', {
			method: 'post',
			postBody: {
				ajax: 'add',
				id: id,
				colour: colour,
				qty: qty,
				price: price
			},
			onComplete: this.updateCart.bind( this )
		} ).request();
	},
	
	updateCart: function( res ) {
		var msg = Json.evaluate( res );
		if( msg.type == 'success' ) {
			new Fx.Scroll( window ).toElement( 'cart' );
			
			$( 'cart_items' ).setHTML( msg.items );
			this.end = parseFloat( msg.total );
			this.updating = parseFloat( $( 'cart_total' ).innerHTML );
			this.updateHTML();
		}
		new mdMsg( ['Emotional Baggage', msg.msg] );
	},
	
	updateHTML: function() {
		if( this.updating <= this.end )
		{
			$( 'cart_total' ).setHTML( this.updating.toFixed( 2 ) )
			setTimeout( this.updateHTML.bind( this ), 1 )
			this.updating = this.updating + .50;
		}
		else
			$( 'cart_total' ).setHTML( this.end.toFixed( 2 ) );
	},
	
	changeQty: function( id, colour, newQty ) {
		this.id = id;
		this.colour = colour;
		new Ajax( 'ajax.php', {
			method: 'post',
			postBody: {
				ajax: 'update',
				id: id,
				colour: colour,
				qty: newQty
			},
			onComplete: this.updateQty.bind( this )
		} ).request();
	},
	
	updateQty: function( res ) {
		msg = Json.evaluate( res );
		if( msg.type == 'error' )
			new mdMsg( ['Emotional Baggage', msg.msg] );
		else {
			$( 'price_' + msg.id ).setHTML( '£ ' + msg.item_total );
			$( 'checkout_total' ).setHTML( parseFloat( msg.total ) );
		}
	},
	
	removeFromCart: function( id, colour ) {
		new Ajax( 'ajax.php', {
			method: 'post',
			postBody: {
				ajax: 'remove',
				id: id,
				colour: colour
			},
			onComplete: function( res ) {
				msg = Json.evaluate( res );
				if( msg.type = 'success' )
					$( 'remove_' + msg.remove ).remove();
				else
					new mdMsg( ['Emotional Baggage', msg.msg] );
			}
		} ).request();
	},
	
	discount: function( el ) {
		code = el.getValue();
		if( code ) {
			new Ajax( 'ajax.php', {
				method: 'post',
				postBody: {
					ajax: 'discount',
					code: code
				},
				onComplete: function( res ) {
					msg = Json.evaluate( res );
					if( msg.type == 'success' ) {
						var total = $( 'checkout_total' ).innerHTML.toFloat();
						var discount = total * msg.amount.toFloat();
						$( 'checkout_total' ).setHTML( ( total - discount ).toFixed( 2 ) );
					}
					else
						new mdMsg( ['Emotional Baggage', msg.msg] );
				},
				onFailure: function( res ) {
					new mdMsg( ['Emotional Baggage', 'There was an unexpected error when trying to prcess your discount code. Please try again.'] );
				}
			} ).request();
		}
	}
	

});

var c = new cart();
