basket = {
	get : function(callback) {
		basket.__request("/udata/emarket/basket.json", {}, callback);
	},
	putElement : function(id, options, callback) {
		basket.__request("/udata/emarket/basket/put/element/" + id + ".json", options, callback);
	},
	modifyItem : function(id, options, callback) {
		if(options.amount == 0) {
			this.removeItem(id, callback);
			return;
		}
		basket.__request("/udata/emarket/basket/put/item/" + id + ".json", options, callback);
	},
	removeElement : function(id, callback) {
		basket.__request("/udata/emarket/basket/remove/element/" + id + ".json", {}, callback);
	},
	removeItem    : function(id, callback) {
		basket.__request("/udata/emarket/basket/remove/item/" + id + ".json", {}, callback);
	},
	removeAll     : function(callback) {
		basket.__request("/udata/emarket/basket/remove_all.json", {}, callback);
	},
	__cleanupHash : function(input) {
		var output = {
			customer : input.customer.object.id,
			items    : input.items,
			summary  : input.summary,
			id	:input.id
		};
		return output;
	},
	__transformOptions : function(options) {
		var o = {};
		for(var i in options) {
			var k;
			if(i.toLowerCase() != "amount") k = "options[" + i + "]";
			else k = i;
			o[k] = options[i];
		}
		return o;
	},
	__request : function(url, options, callback) {
		jsonp(url, basket.__transformOptions(options),
			  function(data){
				  if(callback) callback( basket.__cleanupHash(data) );
			  });
	}
};

window.inArray = function (arr, val) { for(var i=0;i<arr.length;i++) if(arr[i]==val) return true; return false;}

var frontEndBasket = {
	replaceBasket: function (id) {
		return function (e) {
			var text, rem_item = true, stack_ids=[], item_total_price;
			var add_basket_button_text = 'Добавить в корзину';
			var detect_options = {};
			if (e.summary.amount > 0) {
				text = e.summary.price.actual + ' ' + e.summary.price.suffix + '';
				for (var i in e.items.item) {
				var item = e.items.item[i];
					stack_ids.push(item.id);
					if (item.id == id) {
						rem_item = false;
						item_total_price = item["total-price"].actual + ' ' + item["total-price"].suffix;
					}
					if (item.page.id == id) {
						if (detect_options.amount) detect_options.amount = detect_options.amount + item.amount;
						else detect_options = {'id':id, 'amount':item.amount};
					}
				}
				jQuery('table.emarket-cart tr').each( function(){
				var buff = this.className;
					if(buff.indexOf('cart_item_') == 0){
						var d = /[0-9]+/.exec(buff);
						if(!window.inArray(stack_ids,d[0])) jQuery(this).remove();
					}
				});
				if (rem_item) {
					if (jQuery('.cart_item_' + id)) jQuery('.cart_summary').text(e.summary.amount + ' шт, на сумму ' + text);
				} else {
					jQuery('.cart_item_price_' + id).text(item_total_price);
					jQuery('.cart_summary').text(e.summary.amount + ' шт, на сумму ' + text);
				}
				if(jQuery('#s5_dd_buttons').length == 0){
					jQuery('#s5_dropdownback').append('<div id="s5_dd_buttons" style="margin-top:8px"><div onclick="window.document.location.href=\'/emarket/cart/\'" style="font-weight:bold;margin-right:20px; cursor:pointer;color:#000000;float:left;padding:1px;padding-right:21px;background:url(/images/bask/arrow.png) no-repeat center right;font-size:12px">Купить</div></div><div style="clear:both"></div>');
				}
			} else {
				if(jQuery('.basket-block').length) jQuery('.basket-block').parent().html('<p>Корзина пуста</p>');
				jQuery('#s5_dd_buttons').remove();
			}
			jQuery('.bask-amount').text('Товаров: '+e.summary.amount+' шт.');
			if (e.summary.amount==0) text='0';
			jQuery('.bask-price').text('Всего на: '+text);
		};
	},
	add: function (id, val) {
	var opt_s = (val) ? {amount:val} : null;
		basket.putElement(id, opt_s, frontEndBasket.replaceBasket(id));
	},
	modify: function (id, amount_new, amount_old) {
		if (amount_new.replace(/[\d]+/) == 'undefined' && amount_new != amount_old && amount_new != 0) {
			basket.modifyItem(id, { amount: amount_new }, frontEndBasket.replaceBasket(id));
		}
	},
	remove: function (id) {
		basket.removeItem(id, frontEndBasket.replaceBasket(id));
	},
	remove_all: function () {
		basket.removeAll(frontEndBasket.replaceBasket(0));
	},
	repeat_old_order: function (id) {
		var callback = function() { basket.get(frontEndBasket.replaceBasket(id)); };
		basket.repeat_old_order(id, callback);
	},
	basket_refresh: function(){
		basket.get(frontEndBasket.replaceBasket(0));
	}
};
