site.basket = {};

site.basket.replaceBasketPopup = function(id) {
    return function(e) {
       var basketList = jQuery('#TopMenu ol.BasketList');
       var totals = e.summary.amount;
       var detect_options = {};

       if (totals > 0){
           basketList.empty();
           for (i in e.items.item) {
               item = e.items.item[i];

               basketList.append('<a id="' + item.id + 'a" alt="Удалить эту книгу из корзины?" class="BBBClose" onclick="site.basket.remove(' + item.id + ', \'popup\');" href="javascript:void(0)"></a>');
               basketList.append('<li id="' + item.id + 'li">&laquo;' + item.name + '&raquo; - <span class="totalAmount">' + item.amount + '</span> шт.</li>');
           }
           jQuery('#basketTotalSpanBg').text(totals);
           jQuery('#basketTotalSpanFg').text(totals);
           updateCount(totals);
       } else {
         jQuery('#basketTotalSpanBg').text(totals);
         jQuery('#basketTotalSpanFg').text(totals);
         updateCount('0');
         basketList.empty();
         jQuery('#addBasketInfo').empty();
       }
    };
};

site.basket.replaceBasket = function(id) {
    return function(e) {
        jQuery.get('/umap/emarket/cart/', function(data){
           var noActive = jQuery("#issueOrder").hasClass('BtBuyNoActBBB');
           jQuery('#basketWrapper').html(data);
           if (!noActive) jQuery("#issueOrder").removeClass('BtBuyNoActBBB').addClass('BtBuyBBB').attr('href','/basket/issue_order');
        });
    };
};

site.basket.replace = function(id) {
	return function(e) {
		var text, item_total_price, cart_item, basket, i, item,
			cart_summary = jQuery('.cart_summary'),
			add_basket_button_text = 'Добавить в корзину',
			rem_item = true,
			detect_options = {};

		if (e.summary.amount > 0) {
			text = e.summary.price.actual + ' ' + e.summary.price.suffix + '.';
			for (i in e.items.item) {
				item = e.items.item[i];
				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};
				}
			}
			if (detect_options.amount) {
				var add_basket_button = jQuery('#add_basket_' + detect_options.id);
				if (add_basket_button[0].tagName.toUpperCase() == 'A') {
					add_basket_button.text(add_basket_button_text + ' (' + detect_options.amount + ')');
				}
				else add_basket_button.val(add_basket_button_text + ' (' + detect_options.amount + ')');
			}
			if (rem_item) {
				if (cart_item = jQuery('.cart_item_' + id)) {
					cart_item.remove();
					cart_summary.text(text);
				}
			}
			else {
				jQuery('.cart_item_price_' + id).text(item_total_price);
				cart_summary.text(text);
			}
			text = e.summary.amount + ' шт товаров на сумму ' + text;
		}
		else {
			text = 'В корзине нет ни одного товара.';
			if (basket = jQuery('.basket')) {
				basket.text(text);
			}
		}
		jQuery('.basket_info_summary').text(text);
	};
};

site.basket.add = function(id, form, popup) {
	var e_name, options = {};
	if (form) {
		var elements = jQuery(':radio:checked', form);
		for (var i = 0; i < elements.length; i++) {
			e_name = elements[i].name.replace(/^options\[/, '').replace(/\]$/, '');
			options[e_name] = elements[i].value;
		}
	}
	basket.putElement(id, options, this.replace(id));
	if (popup) jQuery('#add_options_' + id).remove();
};

site.basket.list = function(link) {
	var id = (link.id.indexOf('add_basket') != -1) ? link.id.replace(/^add_basket_/, '') : link;
	if (!id) return false;
	if (jQuery(link).hasClass('options_true')) {
		if (jQuery('#add_options_' + id).length == 0) {
			jQuery.ajax({
				url: '/upage//' + id + '?transform=modules/catalog/popup-add-options.xsl',
				dataType: 'html',
				success: function (data) {
					site.message({
						id: 'add_options_' + id,
						header: 'Выбор опций',
						width: 400,
						content: data
					});
				}
			});
		}
	}
	else this.add(id);
};

site.basket.modify = function(id, amount_new, amount_old) {
	if (amount_new.replace(/[\d]+/) == 'undefined' && amount_new != amount_old) {
		basket.modifyItem(id, {amount:amount_new}, this.replace(id));
	}

};

site.basket.remove = function(id, type) {
    if (type == 'popup'){
        if (jQuery("#"+id+"id").length != 0) jQuery('#addBasketInfo').empty();
        basket.removeItem(id, this.replaceBasketPopup(id));
        if (jQuery("#basketWrapper").length) {
            basket.get(site.basket.replaceBasket(id));
        }
    }
    else{
        basket.removeItem(id, this.replaceBasket(id));
        basket.get(site.basket.replaceBasketPopup(id));
    }
	//if (id == 'all') basket.removeAll(this.replace(id));
	//else basket.removeItem(id, this.replace(id));
};

site.basket.init = function() {
	jQuery('.basket_list').click(function(){
		site.basket.list(this);
		return false;
	});
	jQuery('div.basket a.del').click(function(){
		site.basket.remove(this.id);
		return false;
	});
	jQuery('div.basket a.basket_remove_all').click(function(){
		site.basket.remove('all');
		return false;
	});
};

jQuery(document).ready(function(){site.basket.init()});
