var priceAdjustments = new Array();
var currentBundle;

function addCccToCart() {
	for ( i=1 ; i<=currentBundle.length ; ++i ) {
		var classId = options['EW-189C']['Instrument ' + i]['classid'];
		$('#option' + i)
			.attr('name', 'product_options[' + classId + ']')
			.attr('value', options['EW-189C']['Instrument ' + i]['options'][$('#inst' + i).val()]['id']);
	}
	document.addToCart.submit();
}

function calculatePriceDifferences() {
	// calculate price adjustments for each item to each item
	for( i in products ) {
		priceAdjustments[i] = new Array();
		for( j in products ) {
			if( i == j )
				priceAdjustments[i][j] = 0;
			else {
				priceAdjustments[i][j] = products[j]['price'] - products[i]['price'];
			}
		}
	}
}

function updateOptions() {
	// remove any existing options
	$('option', '#bundle').remove();

	// for js "in" operator's sake
	// could keep this as a global and update it, but recreating it seems most simple
	var bundleObjects = objectFromArray(currentBundle);

	// will hold all unselected <option>s
	var options = '';

	// get list of unselected products
	// would be nice to generate this list once, but price diffs change every time
	var unselectedProducts = new Array();
	for ( sku in products ) {
		if ( !(sku in bundleObjects) ) {
			unselectedProducts.push( sku );
		}
	}

	// set each <select>'s lists, with current option first
	for ( i=1 ; i<=currentBundle.length ; ++i ) {
		var selectedSku = currentBundle[i-1];
		var options = '<option class="' + selectedSku + '" value="' + selectedSku + '">' + products[selectedSku]['name'] + ' (or change selection)</option>';

		// now get unselected items, with price differences
		for ( j in unselectedProducts ) {
			var sku = unselectedProducts[j];
			var adjustment = priceAdjustments[selectedSku][sku];
			var adjustmentText = '';
			if( adjustment > 0 ) {
				adjustmentText = ' [Add ' + cursym + adjustment.toFixed(2) + ']';
			}
			else if( adjustment < 0 ) {
				adjustmentText = ' [Subtract ' + cursym + (-adjustment).toFixed(2) + ']';
			}
			options += '<option class="' + sku + '" value="' + sku + '">' + products[sku]['name'] + adjustmentText + '</option>';
		}
		$('#inst' + i).html( options );
	}
}

function updateTotals() {
	var listPrice = 0;
	var yourPrice = baseBundlePrice;

	for ( i=0 ; i<currentBundle.length ; ++i ) {

		var sku = currentBundle[i];

		listPrice += products[sku]['list'];

		// add price difference to base bundle price
		yourPrice += priceAdjustments[defaultBundle[i]][sku];
	}

	$("#bundle-list-price").html( listPrice.toFixed(2) );
	$("#bundle-your-price").html( yourPrice.toFixed(2) );
}

function selectProduct( p ) {
	var id = parseInt(p.id.replace( /^inst/, '' )) - 1;
	if( id >= 0 && id < currentBundle.length ) {
		var sku = $('option:selected', p).val();

		if( sku != undefined )
			currentBundle[id] = sku;

		updateOptions();
		updateTotals();

		var liParent = $(p).parents("li").get(0);

		// update the image
		$('img', liParent ).attr( 'src', '/image.php?productid=' + sku ).attr( 'alt', products[sku]['name'] );

		// update the href
		$('a', liParent ).attr( 'href', '/product.php?productid=' + sku );

		// update the mini-list
		var instrumentId = p.id.replace(/^inst/, '');
		var newText = sku + ': ' + products[sku]['name'];
		$('#your-instrument-' + instrumentId).css('color','#FC3').fadeOut('fast', function() {
			$('#your-instrument-' + instrumentId).html(newText).fadeIn('fast', function() {
				$('#your-instrument-' + instrumentId).css('color','#FFF');
				$('#bundle-your-container').css('color','#FFF');
			});
		});

		// blur the <select> for IE's sake
		$('#add_button').focus();
	}
}

function objectFromArray(a) {
	var o = {};
	for(var i=0;i<a.length;++i)
		o[a[i]]='';
	return o;
}

$(document).ready(function() {

	calculatePriceDifferences();

	currentBundle = defaultBundle.slice();

	$('select', '#bundle').change( function() { selectProduct( this ) } );

	updateOptions();

	$('select', '#bundle').change();
});

