﻿var loader = null;
var bottomButtons = null;
window.addEvent('domready', function() {
	loader = Asset.image(static + '/images/ajax-loader.gif');
	$('form').addEvent('submit', function(e) {
		e.stop();
		if ($('quantityBox').value < 0) return;
		addButton = $('addButtons').getFirst();
		bottomButtons = $('bottomButtons').getFirst();
		$('addButtons').empty();
		loader.clone().inject('addButtons');
		this.async.value = true;
		this.set('send', {
			onComplete: function(resp, text) {
				var obj = JSON.decode(resp);
				if (obj.IsUpdate && $chk($('item_' + obj.FldKey)))
					LM.CartFunctions.UpdateItem(obj);
				else
					LM.CartFunctions.AddItem(obj);
				$('addButtons').empty();
				addButton.inject($('addButtons'));
				if (!$('bottomButtons').getLast().hasClass('checkoutBtn')) {
					// add a checkout button if there is not already one
					var checkoutButton = new Element('a', {
						'class': 'checkoutBtn',
						href: path + '/checkout'
					}).adopt(new Element('span', {
						html: 'Checkout'
					}));
					checkoutButton.inject('bottomButtons', 'bottom');
				}
			}
		});
		this.send();
	});
	$$('form.shopItem').addEvent('submit', function(e) {
		e.stop();
		button = this.getElement('input[type=submit]').dispose();
		loader.clone().inject(this);
		this.async.value = true;
		this.set('send', {
			onComplete: LM.CartFunctions.UpdateLoader.bind(this)
		});
		this.send();
	});

	$('subIssue').addEvent('change', function() {
		new Request.HTML({
			url: path + '/shop/subscriptions/price.rails',
			update: "subPrice"
		}).post({
			"issue": $('subIssue').value,
			"id": $('subID').value
		});
	});
	$$('#imageGroup img').addEvent('click', function() {
		Slimbox.open(this.src, this.title);
	});
});

