
var Voucher = {
	request: function(code) {
		var url = "xhr_vouchers.asp";
		new Ajax.Request(url, {
			method: 'post',
			parameters: 'code='+code,
			evalJSON: true,
			onFailure: this.failed,
			onSuccess: this.apply
		});
	},
	apply: function(t) {
		var json = t.responseText.evalJSON();
		//console.log(json);

		if(json.error) {
			$('voucher-value').update(json.error);
			$('subtotal').update(json.subTotal);
			$('vat').update(json.vat);
			$('total').update(json.grandTotal);
		}
		else if(json.voucherValue) {
			$('voucher-value').update(json.voucherValue);
			$('subtotal').update(json.subTotal);

			$('vat').update(json.vat);
			if($('hid_vat')) {
				$('hid_vat').value = json.vat.replace(/[^0-9.]/g);
			}

			$('total').update(json.grandTotal);
			if($('hid_ordertotal')) {
				$('hid_ordertotal').value = json.grandTotal.replace(/[^0-9.]/g);
			}
		}
	},
	failed: function(t) {
		alert('Voucher request failed. Please try again');
	}
}

document.observe("dom:loaded", function() {
	var el = $('voucher-code');
	if(el && el.value) {
		Voucher.request(el.value);
	}
});
