DAW = {
	
	error_msg: function(msg) {
		alert(msg);
	},
	
	say_thanks: function() {
		$(document).ready(function(){
			$('#content').prepend('<div class="daw-thanks"><h3>Thanks for your order!</h3><p>You should receive a confirmation email shortly.</p></div>');
		});
	},
	
	update_total: function($form) {
		params = {
			action: 'daw_calc_total',
			qty: $form.find('.daw_buyer_qty').val(),
			domestic: $form.find('.daw_domestic').val(),
			product_id: $form.find('.product_id').val()
		};
		$.get(DAW_SITEURL, params, function(data){
			$form.find('.total-price .value').html('<strong>' + data.total + ' <small>total</small></strong> <em>(' + data.subtotal + ' + ' + data.shipping + ' shipping)</em>');
		}, 'json');
	},
	
	validate_qty: function($form) {
		$qty = $form.find('.daw_buyer_qty');
		buyer_qty = parseInt($qty.val());
		qty_available = parseInt($form.find('.qty-available strong').text().replace(/,/, ''));
		if ( buyer_qty < 1 ) {
			$qty.val(1);
		}
		else if ( buyer_qty > qty_available ) {
			$qty.val(qty_available);
		}
	},
	
	init: function() {
		$(document).ready(function(){
			
			// update total when qty or shipping location is changed
			$('.daw_buyer_qty, .daw_domestic').change(function(){
				$form = $(this).closest('form.daw-form');
				// make sure quantity is within bounds
				DAW.validate_qty($form);
				DAW.update_total($form);
			});
			
			// make sure all forms have valid totals on page load
			$.each($('.daw-form'), function(){
				$form = $(this);
				DAW.update_total($form);
			});
			
		});
	}
};

$ = jQuery;
DAW.init();