FP.Order = {
	ajax: {},
	click_counter: {},
	values: {},
	timeout: {},
	changeQuantity: function(input) {
		if (input.value == '') return false;
		if (!(input.name in this.values)) {
			this.values[input.name] = '';
			this.click_counter[input.name] = 0;
		}

		if (this.values[input.name] != input.value) { // dont continue if value didnt change
			this.values[input.name] = input.value;
			this.click_counter[input.name]++;

			this.timeout[input.name] = window.setTimeout(function() {
				this._changeQuantity(input, Number(this.click_counter[input.name]));
			}.bind(this), 200);
		}
		return false;
	},

	_changeQuantity: function(input, click_count) {
		if (this.click_counter[input.name] == click_count) {
			if (input.name in this.ajax && this.ajax[input.name].transport) {
				this.ajax[input.name].transport.abort();
			}
			clearTimeout(this.timeout[input.name]);

			this.ajax[input.name] = this._submitQuantityChange(input.name.split('_')[1], input.value);
		}
		return false;
	},

	_submitQuantityChange: function(issue_id, quantity) {
		var input = $('item_' + issue_id);
		return new Ajax.Request('/order/quantity/' + issue_id + '/' + quantity, {
			onLoading: function() {
				$('loading_' + issue_id).show();
			},
			onComplete: function(transport, json) {
				$('loading_' + issue_id).hide();
				delete(this.ajax[input.name]);
			}.bind(this)
		});
	},

	changeCountry: function(select) {
		new Ajax.Request('/order/change_country/' + $F(select));
	},

	noEnter: function(e) {
		var code = e.keyCode || e.which;
		// apple keyboard returns 3 for the small return key...
		if (code == 13 || code == 3) return false;
	}
};


// behaviors
Event.addBehavior({
	'.issue .text:keyup': function(e) {
		return FP.Order.changeQuantity(this);
	},

	'.issue .text:keypress': function(e) {
		return FP.Order.noEnter(e);
	},

	'#order_address_country:change': function(e) {
		FP.Order.changeCountry(this);
	}
});