$( function() {
	$('#content table tr td.qty a.up').click( function() {
		
		var i = $(this).next('input');
		
		var next = parseInt(i.val())+1;
		
		if(next < 100) i.val(next);
		
		subtotal();
		
		return false;
		
	});
	
	$('#content table tr td.qty a.down').click( function() {
		
		var i = $(this).prev('input');
		
		var next = parseInt(i.val())-1;
		
		if(next > -1) i.val(next);
		
		subtotal();
		
		return false;
		
	});
	
	$('#content table tr td.qty select').change( subtotal );
	
	subtotal();
	
});

function subtotal() {
	
	var empty = "y";
	
	var total_price = 0.0;
	
	//$('#content').prepend('Get total');
	
	$('#content fieldset.subtotal table').remove();
	$('#content fieldset.subtotal p.empty').before('<table></table>');
	
	$('#content table tr td.qty select').each( function() {
		
		if($(this).val() > 0) {
			
			var category = $('#content h2[title='+ $(this).attr('rel') +']').text();
			
			var product = $(this).parent().parent().find('td').eq(0).html();
			
			if($(this).attr('title') != '') {

				var variant = '<br/><span>'+ $(this).attr('title') +'</span>';
				
			} else {
				
				var variant = '';
				
			}
			
			
			var price_number = parseFloat($(this).parent().prev('td').attr('title'));
			
			var price_text = $(this).parent().prev('td').html();
			
			var qty = parseInt($(this).val());
			
			//$('#content').prepend('Product: '+ product);
			
			var price = real_price(price_number*qty);
			
			add_to_total(category, product, variant, price, qty);
			
			total_price += price_number*qty;
			
			empty = "n";
			
		}
		
	});
	
	if(empty == "n") {
		
		total_price = real_price(total_price);

		$('#content fieldset.subtotal table').append('<tr class="total"><td colspan="2" class="text"></td><td class="price">Total: &pound;'+ total_price +'</td>');
		
		$('#content fieldset.subtotal p.empty').hide();
		
		$('#content fieldset.subtotal input.clickable').show();
		
	} else {
		
		$('#content fieldset.subtotal table').remove();
		
		$('#content fieldset.subtotal p.empty').show();
		
		$('#content fieldset.subtotal input.clickable').hide();
		
	}
	
};

function real_price(num) {

	//var total = Math.round( Math.round( num * Math.pow( 10, 2 + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,2);
	
	var total = num.toFixed(2);
	
	return total;
	
};


function add_to_total(category, product, variant, price, qty) {
	
	//$('#content').prepend('Category: '+ category +', Product: '+ product +', Variant: '+ variant +', Price: '+ price +', Qty: '+ qty +'<br/>');
		
	$('#content fieldset.subtotal table').append('<tr class="item"><td class="qty">'+ qty +'x</td><td class="product">'+ category +' - '+ product + variant +'</td><td class="price">&pound;'+ price +'</td>');
	
};
