/**
 * Add a function for validating the event block to the form object
 * 
 * @author Joshua Smith
 * 
 * @param {String} prefix The prefix of the block, including the section prefix. Will be used to build the name of the form fields
 * @param {Boolean} required Indicates whether or not the fields are required for the form
 */

/**
 *
 */
function initShoppingBlock()
{
	$.validator.addClassRules("shopping-basket-block_amount", { digits:true /* , minlength:5 */ });
	
	/**
	 * The use of actual block ids could potentially speed this up
	 * significantly since traversal methods could be replaced with id selectors
	 */
	$('.shopping-basket-block_amount').change(function () {
			var currVal = $(this).val();
			var rowInputs = $(this).parent().parent().parent().find('input');
			// get price from previous control
			var price = rowInputs[1].value;
			var subtotal = price * currVal;
			var extendedPrice = $(this).parent().parent().parent().find('h3.extended_price');
			$(extendedPrice).html((currVal < 0 || isNaN(subtotal)) ? '&nbsp;' : ('$' + subtotal.toFixed(2)));
			updateTotal();
		});
	
	var updateSingleItemTotal = function () {
		// @todo This is executed twice to accomodate for IE not executing it at all the first time
		// (it should only be needed for the 'change' event
		var total = $('.form_block_shopping_basket.singleItem input[type="radio"]:checked')
		.parent().find('input.price').val();
		
		$('.total').html('$' + parseFloat(total, 10).toFixed(2));
	};
	
	$('.form_block_shopping_basket.singleItem input[type="radio"]').change(updateSingleItemTotal).click(updateSingleItemTotal);
}

/**
 *
 */
function updateTotal()
{
	var total = 0;
	$('h3.extended_price').each(function () {
		// strip off the $
		var currVal = parseFloat($(this).html().substr(1),10);
		
		if (!isNaN(currVal)) {
			total += currVal;
		}
	});
	
	$('.total').html('$' + total.toFixed(2));
}

/**
 *
 */
function updateSubtotals()
{
	$('.shopping-basket-block_amount').change();
}

/**
 *
 */
function initColorbox()
{
	try {
		$('.form_block_shopping_basket a.colorbox').colorbox();
	} catch (e) {
		//Do nothing
	}
}

$(document).ready(function () {
	initShoppingBlock();
	updateSubtotals();
	initColorbox();
});
