var AjaxBasket = {
	
	updatePage: function(response){
		var topnav = $('#topnav');
		
		if(topnav && topnav.length){
			topnav.find('.cart-items').html(response.items ? _lang.products_in_basket+': <strong>'+response.items+'</strong>' : _lang.basket_is_empty);
		}
		
		$('.block-basket').each(function(){
			var id = $(this).parent().parent().attr('id').match(/[\d]+$/)[0];
			var wrap = $(this).parent();
			
			$.get(_base+'default/ajaxbasket_block/'+id, {}, function(html){
				if(html){
					wrap.html(html);
				}
			});
		});
	},
	
	showBubble: function(target_el, response){
		target_el = $(target_el);
		
		var offset = target_el.offset();
		var bubble = $('<div class="ajaxbasket-bubble"><div class="ajaxbasket-content"></div><div class="ajaxbasket-footer"></div>');
		var details = $('<div class="ajaxbasket-details">'+_lang.ajaxbasket_items+': '+(response.items)+', '+_lang.ajaxbasket_total+': '+displayPrice(response.total)+'</div>')
		
		bubble.find('.ajaxbasket-content').html(response.msg).append(details);
		
		if(response.page_basket){
			var link = $('<a href="'+response.page_basket+'">'+_lang.ajaxbasket_go_to_basket+'</a>');
			bubble.find('.ajaxbasket-footer').append(link);
		}
		
		$('.ajaxbasket-bubble').remove();
		$('body').append(bubble);
		
		bubble.css({
			top: offset.top + 5,
			left: offset.left - 10
			
		}).fadeIn();
		
		AjaxBasket.updatePage(response);
		
		setTimeout(function(){
			bubble.fadeOut(function(){
				bubble.remove();
			});
		}, 4500);
	},
	
	addToBasket: function(data, btn, allow_redirect){
		if(btn){
			$(btn).attr('disabled', true);
		}
	
		$.post(_base+'default/ajaxbasket', data, function(response){
			
			if(response){
				if(btn){
					if(! response.status && response.has_attributes && allow_redirect){
						window.location = response.redirect;
						return;
					}
					
					$(btn).removeAttr('disabled');
				
					AjaxBasket.showBubble(btn, response);
				}
				
			}else{
				alert('Unknown error');
			}
			
		}, 'json');
	}
	
}

$(function(){
	
	$('button.buy').bind('click', function(){
		var data = $(this).parents('form:first').serializeArray();

		AjaxBasket.addToBasket(data, this);
		
		return false;
	});
	
	$('a.buy').bind('click', function(){
		var product_id = $(this).attr('href').match(/buy\=([\d]+)/)[1];
		
		if(product_id){
			AjaxBasket.addToBasket({
				product_id: product_id,
				qty: 1
			}, this, true);
			
			return false;
		}
	});
	
});
