
/**
 * Load the product description area when a gallery item is clicked
 * @param gallery_image_element The actual <img> element from the gallery list
 * @return void
 */
function loadProductDetail(gallery_image_element) {
	var section = '';
	var image_name = '';
	var item_code = '';

	//
	// Turn it into jQuery
	//
	var jquery_gallery_image_element = $(gallery_image_element);

	var path = jquery_gallery_image_element.attr('src');
	path = path.split('/');
	for (i in path) {
		if (path[i].substr(0, 5) == 'data.') {
			section = path[i].substr(5);
		}
		image_name = path[i]; // we just want the last one
	}

	// '_thumb.jpg' or whatever is always 10 characters
	item_code = image_name.substr(0, image_name.length - 10);

	$.ajax({
		url: 'http://www.taylorkenney.com/shop/detail.php?item_code='+item_code+'&shop='+section
		, type: 'GET'
		, dataType: 'text'
		, timeout: 1000
		, success: function(result) {
			if (result != '') {
				$("#productDetail").html(result);
			}
		}
		, error: function(result) {
			loadProduct(gallery_image_element);
		}
	});
}

/**
 * Add the current item in the detail area to the shopping cart.
 */
function addToCart() {
	var itemCode = $('#itemCode').val();
	var quantity = $('#itemQuantity').val();

	$.ajax({
		url: 'http://www.taylorkenney.com/shop/cart.php?action=add&itemCode='+itemCode+'&quantity='+quantity
		, type: 'GET'
		, dataType: 'text'
		, timeout: 1000
		, success: function() {
			updateCartWidget();
		}
		, error: function(XMLHttpRequest, textStatus, errorThrown) {
			addToCart();
		}
	});
}

/**
 * comments
 */
function updateCartWidget() {
	$.ajax({
		url: 'http://www.taylorkenney.com/shop/cart.php?action=current'
		, type: 'GET'
		, dataType: 'text'
		, timeout: 1000
		, success: function(result) {
			result = eval('('+result+')');
			$('#cartWidget #totalItems').html(result['totalItems']);
			$('#cartWidget #subtotal').html(result['subtotal']);
		return;
		}
		, error: function(XMLHttpRequest, textStatus, errorThrown) {
			updateCartWidget();
		}
	});
}

/**
 * comments
 */
function updateCartTotals() {
	var cartTable = $('#cartTable');
	var quantity = {};
	cartTable.children().each(function() {
		var table = $(this);
		table.children().each(function() {
			var row = $(this);
			row.children().each(function() {
				var cell = $(this);
				if (cell.attr('class') == 'quantity') {
					cell.children().each(function() {
						var quantityElement = $(this);
						quantity['items['+row.attr('id')+']'] = quantityElement.val();
					});
				}
			});
		});
	});

	$.ajax({
		url: 'http://www.taylorkenney.com/shop/cart.php?action=update&'
		, type: 'GET'
		, dataType: 'text'
		, data: quantity
		, timeout: 1000
		, success: function(result) {
//			alert('got here');
			location.reload(true);
		}
		, error: function(XMLHttpRequest, textStatus, errorThrown) {
			updateCartTotals();
		}
	});


//	for (i in quantity) {
//		alert('quantity['+i+'] = '+quantity[i]);
//	}
}