$(document).ready( function() {
	
	// COLORBOX SETTINGS
	$('#book-image').colorbox({
		maxWidth: '90%',
		maxHeight: '90%',
    });
	
	// CART AJAX
	// Display working.gif but hide it
	$('#cart-buttons').prepend('<img id="working-gif" style="visibility: hidden;" src="style/images/working.gif" />');
	
	$(':input').change( function() {
		
		var data = $('form').serialize();
		data = data+'&ajax=1';
		
		// Show working.gif
		$('#working-gif').css('visibility', 'visible');
		
		// Remove errors from previous calls
		$('.cart-error').slideUp('fast', function() {
			$(this).remove();
		});
		
		// Now let's send our data to the server
		$.ajax({
			data: data,
			url: 'cart/ajax',
			type: 'POST',
			success: updatePage,
		});
		
		function updatePage(data, textStatus) {
			if (textStatus == 'success') {
				var updatedData = $.parseJSON(data);
				var rowids = new Array();
				for (var property in updatedData) {
					
					// Let's update each row
					if (typeof(updatedData[property]) == 'object') {
						$('#'+property+' :input').val(updatedData[property]['qty']);
						$('#'+property+' .subtotal').html(updatedData[property]['subtotal']);
						rowids.push(property);
					}
					
					// Update shipping
					if (property == 'postage') {
						$('tr.shipping .price').html(updatedData[property]);
					}
					
					// Update total
					if (property == 'total') {
						$('.total-field').html(updatedData[property]);
					}
					
					// Show errors
					if (property == 'error') {
						$('form').before(updatedData[property]);
						$('.cart-error').slideDown('fast');
					}
				}
			}
			
			// Remove deleted cart items
			$('.cart-item').each( function() {
				var current_rowid = $(this).attr('id');
				var match = false;
				for( var i = 0; i < rowids.length; i++) {
					if (current_rowid == rowids[i]) {
						match = true;
					}
				}
				if (match == false) {
					$('#'+current_rowid).hide('slow', function() {
						$(this).remove();
					});
				}
			});
			
			// Remove working.gif
			$('#working-gif').css('visibility', 'hidden');
		}
		
	});
});
