window.addEvent('domready', function() {
	var updateCartMitem = function(total, price) {
		var liShop = $$('#menu li.shop')[0];
		if(!$chk(liShop)) {
			liShop = new Element('li', {'class': 'last shop'})
			.adopt(
				new Element('a', {href: '/shop/'})
				.set('html', 'Корзина: <span class="value">' + price +'</span> &#8364;')
			)
			.inject($('menu'));
		}

		if (total < 1) {
			liShop.set('tween', {onComplete: function() { liShop.dispose(); } }).fade('out');
		} else {
			$$('#menu li.shop span.value')[0].set('text', price);
			liShop.highlight();
		}
	}


	try {
		var updateTotals = function(total, price) {
			var liShop = $$('#menu li.shop')[0];
			if (total < 1) {
				$('thebasketpage').set('tween', {onComplete: function() { $('thebasketpage').empty().set('html', '<p>Ваша корзина пуста</p>'); } }).highlight();
			} else {
				$$('#basketlist tr.grandtotal td.price').set('html', price + ' &euro;').highlight();
			}
			updateCartMitem(total, price);
		};

		$$('#basketlist tr.bitem').each(function(ShopItem) {
			var delLink = ShopItem.getElements('a.del')[0];
			var did = delLink.get('href').match(/\/del\/(.*?)$/)[1];

			delLink.addEvent('click', function(e) {
				var delRequest = new Request.JSON({url: "del/"+did, onSuccess: function(response) {
					if ($chk(response.result)) {
						ShopItem.set('tween', {onComplete: function() { ShopItem.dispose(); } }).fade('out');
						updateTotals(response.count, response.total);
					}
				}}).get({rjson: 1});
				return false;
			});
		});
	}
	catch(e) {}

	try {
		var zid = $$('.ptag input')[0].get('rel');
		$('cform').set('send', {url: "/shop/buy/"+zid+"?rjson=1", onSuccess: function(response) {
			response = JSON.decode(response);
			if ($chk(response.result)) {
				updateCartMitem(response.count, response.total);
				updateTotals(response.count, response.total);
			}

			var icform = $('cform');


			icform.getElements('input.gbtn').each(function(i) {
				i.setStyle('color', '#00ff00').tween('color', '#000000');
			});


		}, method: 'post'});

		$$('.ptag input').each(function(buyBtn){
			buyBtn.addEvent('click', function() {
				$('cform').send();
				return false;
			});
		});
	}
	catch(e) { }
});
