var cart = {
	locked: false,

	//добавить
	add: function(item_type, item_id, type, quantity, data)
	{
		item_type 	= item_type ? item_type : 'book';
		item_id 	= Number(item_id);
		type 		= type ? type : 'in_cart';
		quantity	= quantity ? Number(quantity) : 1;
		
		var post = {
			'item_type'	: item_type ? item_type : 'book',
			'item_id'	: Number(item_id),
			'type'		: type ? type : 'in_cart',
			'quantity'	: quantity ? Number(quantity) : 1
		};
		
		if(data) $.extend(post, {'data[]': data});
		
		$.getJSON('/cart/add/', post,
			function(obj)
			{
				cart.update_cart(obj);
				
				switch(item_type)
				{
					case 'period':
						//main_card
						$btns = $('#card').find('#period_buttons');
						$btns.find('.in_cart').show();
						$btns.find('.to_cart').hide();
						
						//small_card
						$card = $('DIV.card[book_id='+item_id+'] DIV.card_add_book');
						$card.find('.to_cart').hide();
						$card.find('.in_cart').show();
						
						//update
						update_cards(item_id, 'in_cart');
					break;
					
					case 'post_subscription':
						//main_card
						$btns = $('#card').find('#buttons');
						$btns.find('.in_cart').show();
						$btns.find('.to_cart').hide();
						
						//small_card
						$card = $('DIV.card[book_id='+item_id+'] DIV.card_add_book');
						$card.find('.to_cart').hide();
						$card.find('.in_cart').show();
					break;
					
					case 'e_book':
						$('div.card[e_book_id='+item_id+']').removeClass('in_cart deferred').addClass(type);
						
						//некоторые хаки, чтобы не ебаться с версткой
						//хвала богам, которые придумали jQuery хД
						$('#card').find('#e_books div[e_book_id='+item_id+'] > span').toggleClass('hidden');
					break;
				}
			}
		);
	},
	
	//изменить (тип или кол-во)
	edit: function(id, type, quantity, data)
	{
		var post = {
			'id': id,
			'type': type ? type : '',
			'quantity': quantity ? quantity : ''
		};
		
		if(data) $.extend(post, {'data[]' : data});
		
		$.getJSON('/cart/edit/', post,
			function(obj)
			{
				cart.update_cart(obj);
			}
		);
	},
	
	edit_multi: function(ids, type, quantity)
	{
		if (!confirm("Вернуть товары на Шведский стол?")) return;
		
		$.getJSON(
			'/cart/edit/',
			{
				'id[]': ids,
				type: type ? type : '',
				quantity: quantity ? quantity : ''
			},
			function(obj)
			{
				//window.location.reload(true);
				window.location = '/desk/';
			}
		);
	},
	
	//удалить
	del: function(id)
	{
		if (!confirm("Удалить товар?")) return;
		
		$.getJSON(
			'/cart/del/',
			{
				id: id
			},
			function(obj)
			{
				cart.update_cart(obj);
				cart.remove_row(id);
			}
		);
	},
	
    del_selected: function(ids){
		if(!confirm("Удалить товар(ы)?")) return;
		
       var todel = new Array();
       var i = 0;
       var rr = new Array();
        
        for ( var id in ids ) {
            if(ids[id].indexOf( 'desk', 0 ) >= 0)
            {
                rr = ids[id].split('_');
                rr.splice(0, 1);
                $.merge(todel, rr);
                i += rr.length;
            }
            else
                todel[i] = ids[id];
            i++;
        }     
        
		$.getJSON(
			'/cart/del/',
			{
				'id[]': todel
			},
			function(obj)
			{
				cart.update_cart(obj);
                for ( var id in ids ) {
                    cart.remove_row(ids[id]);
                }
			}
		);        
    },
    
    del_all: function(type, msg)
	{
		if(!confirm('Удалить все товары?')) return;
		
		$.getJSON(
			'/cart/del_all/',
			{
				type: type ? type : 'in_cart'
			},
			function(obj)
			{
				window.location.reload(true);
			}
		);
	},
    
	del_multi: function(ids)
	{
		if(!confirm("Удалить комплект?")) return;
		
		$.getJSON(
			'/cart/del/',
			{
				'id[]': ids
			},
			function(obj)
			{
				window.location.reload(true);
			}
		);
	},
	
	deferred: function(id)
	{
		if(!confirm('Перенести товар в отложенные?')) return;
		
		$.getJSON(
			'/cart/edit/',
			{
				id: id,
				type: 'deferred'
			},
			function(obj)
			{
				cart.update_cart(obj);
				cart.remove_row(id);
			}
		);
	},
    
	deferred_selected: function(ids)
	{
		if(!confirm('Перенести товар(ы) в отложенные?')) return;
		
		$.getJSON(
			'/cart/edit/',
			{
				'id[]': ids,
				type: 'deferred'
			},
			function(obj)
			{
				cart.update_cart(obj);
                for ( var id in ids ) {
                    cart.remove_row(ids[id]);
                }
			}             
		);
	}, 

	deferred_all: function()
	{
		if(!confirm('Перенести все товары в отложенные?')) return;
		
		$.getJSON(
			'/cart/deferred_all/',
			{
			},
			function(obj)
			{
				window.location.reload(true);
			}
		);
	},

	quantity: function(id, quantity)
	{
		$.getJSON(
			'/cart/edit/',
			{
				id: id,
				quantity: quantity
			},
			function(obj)
			{
				cart.update_cart(obj);
			}
		);
	},
	
	quantity_rel: function(id, rel)
	{
		var val = $('#cart tr[cart_item_id='+id+'] td.quantity input').val();
		cart.quantity(id, Number(val) + rel);
	},
	
	//обновить корзину
	update_cart: function(obj)
	{
		if(typeof(obj.total) != 'object')
		{
			return;
		}
		
		$("#total_price").text(obj.total.price);
		$("#total_discounted_price").text(obj.total.discounted_price);
		$("#total_quantity").text(obj.total.quantity).show();
		$("#total_shipment_str").text(obj.total.shipment_str);
		$("#weight").text(obj.total.weight);
		
		$("#price_in_text").text(obj.total.rub_discounted_price);
		$("#economy").text(obj.total.rub_price - obj.total.rub_discounted_price);
		
		$("#price_in_text_bb").text(obj.total.rub_price);
		
		if($('#cart').size())
		{
			var $all_rows = $('#cart [cart_item_id]');
			
			//апдейт рядов
			for(id in obj.rows)
			{
				var $tr = $all_rows.filter('[cart_item_id='+id+']');
				var row = obj.rows[id];
				
				$tr.find('.quantity input').val(row.quantity);
				$tr.find('.minus img').toggle(row.quantity > 1);
				
				$tr.find('.price').text(row.price);
				$tr.find('.discounted_price span').text(row.discounted_price);
				
				switch(row.item_type)
				{
					case 'book':
						if(row.quantity >= 25)
						{
							if(!$tr.find('#h357').size())
							{
								var help_tip = $("<img />").attr("src", "/images/help8.gif").addClass("help_label").attr("id", "h357").css("margin-left", "5px");
								$tr.find('td.discounted_price').append(help_tip);
								set_help_tip(help_tip);
							}
						}
						else
						{
							$tr.find('#h357').remove();
						}
					break;
					
					case 'period':
						$tr.find('.month_sel .start').val(row.data[0]);
						$tr.find('.month_sel .end').val(row.data[1]);
						
						$tr.find('td.price').text(row.price_number + ' х ' + row.interval_numbers + ' вып.');
					break;
					
					case 'bonus':
						//if(row.data == '1165492')
						//{
                        if(row.quantity > 1){
                            $('a[book_id='+ row.data +']').closest('table').find('SPAN.bonus_quantity').text(row.quantity + ' шт.');
                            $('a[book_id='+ row.data +']').closest('table').find('SPAN.bonus_span').show();
                        }else{
                            $('a[book_id='+ row.data +']').closest('table').find('SPAN.bonus_span').hide();
                        }
						//}
					break;
				}
			}
			
			//giftwrap hide
			$all_rows.filter('[type=giftwrap]').each(function()
			{
				$(this).toggle(obj.rows[$(this).attr('cart_item_id')] !== undefined);
			});
			
			if($all_rows.filter(':visible').size() == 0)
			{
				window.location.reload(true);
			}
			
			$all_rows.removeAttr('updated');
			
			//апдейт бонусов!
			for(id in obj.bonus)
			{
				$('#cart .bonus[bonus_id='+id+']').toggle(obj.bonus[id]);
			}
			if (obj.tokens.used_books == undefined) {
				$('#id_form_step1').unbind('submit.used_books');				
			}
			if (obj.tokens.book_on_demand == undefined) {
				$('#id_form_step1').unbind('submit.book_on_demand');				
			}		
			if (obj.tokens.post_subscription == undefined) {
				$('#id_form_step1').unbind('submit.post_subscription');				
			}            
			if (obj.tokens.sertificate == undefined) {
				$('#id_form_step1').unbind('submit.sertificate');				
			}   			
		}
		
		for (key in obj.total)
		{
			if(typeof(obj.total[key]) != 'object')
			{			
				$("#cart_"+key).text(obj.total[key]);
			}
		}
		
		$("#shopping_cart_price, #go_to_cart").toggleClass("hidden", !obj.total.price);
		$("#shopping_cart_discounted_price").toggleClass("hidden", !obj.total.discounted_price);

		var quantity = Number(obj.total.quantity);
		//holiday
		//if(quantity > 2) quantity = 2;
		//$("#shopping_cart_img img:first").attr("src", "/images/bag"+quantity+".png");
		if(quantity > 1) quantity = 1;
		$("#shopping_cart_img img:first").attr("src", "/images/holidays/14022012/bag_sv"+quantity+".png");
		
		//единый вывод ошибок
		if(obj.errors != undefined)
		{
			for (i in obj.errors)
			{
				alert(obj.errors[i]);
			}
		}
	},
	
	remove_row: function(id)
	{
		if($('#cart tr[cart_item_id]').size() > 1)
		{
			$('#cart tr[cart_item_id='+id+']').remove();
		}
		else //это последний ряд
		{
			window.location.reload(true);
		}
	},
	
	update_period: function(id, autofix)
	{
		var $tr = $('#cart tr[cart_item_id='+id+']');
		
		var start 		= $tr.find('SELECT.start').val();
		var interval 	= $tr.find('SELECT.interval').val();
		
		cart.edit(id, null, null, [start, interval]);
	}
}
