$(document).ready(function() {
	
	function addCommas(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	
	$('.artwork-popup').click(function(e) {
		var link = $(this);
		show_dialog('artwork', function(result) {
			link.parent().parent().find('.warning img').css('display', 'none');
			link.parent().html('<input type="hidden" name="artwork_id[]" value="' + result.artwork_id + '" /><img src="/artwork/get/' + result.artwork_id + '/thumbnail" style="height: 48px;" />');
			link.parent().find('img').fadeIn(400);
			$('.exhibition-form').submit();
		});
		
		e.preventDefault();
	});
	
	$('.update').click(function(e) {
		$('.exhibition-form').submit();
		
		e.preventDefault();
	});
	
	$('select.shipping').change(function() {
		var text = $(this).find('option:selected').text();
		var subtotal = parseFloat($('table.total td.subtotal').text().match(/[0-9\.\,]+$/)[0].replace(',', ''));
		var weight = parseFloat($('table.total td.weight').text().match(/^[0-9\.]+/));
		var weight_extra = 0;
		if (weight > 20) {
			weight_extra = Math.ceil(weight - 20) * 0.50;
		}
		
		var ship_value = parseFloat(text.match(/[0-9\.]+$/));
		ship_value += weight_extra;
		var total_value = 0;
		if (weight_extra)
			$('table.total td.delivery div.extra').text("+ £" + addCommas((weight_extra).toFixed(2)));
		else
			$('table.total td.delivery div.extra').text('');
		$('table.total td.tax').text("£" + addCommas(((ship_value / 100) * 15 + (subtotal / 100) * 15).toFixed(2)))
		$('table.total td.value').each(function() {
			total_value += parseFloat($(this).text().match(/[0-9\.\,]+$/)[0].replace(',', ''));
		});
		if (ship_value)
			total_value += ship_value;
		$('table.total tr.gtotal td.total').text("£" + addCommas(total_value.toFixed(2)));
	});
	
	$('.go-checkout').click(function(e) { $('.go-checkout-form').submit(); e.preventDefault(); });
});