var inCart = false;
var inCartHeader = false;
var contentTop = 0;

$(document).ready(function() {
	$('#header_cart').mouseenter(function() {
		inCartHeader = true;
		Cart.expand();
	}).mouseleave(function() {
		setTimeout(function() {
			inCartHeader = false;
			checkCart();
		}, 100);
	});
	
	$('#cart').mouseenter(function() {
		inCart = true;
	}).mouseleave(function() {
		setTimeout(function() {
			inCart = false;
			checkCart();
		}, 100);
	});
});


function checkCart() {
	if (!inCart && !inCartHeader) {
		Cart.collapse();
	}
}

var expanded = false;

Cart = {
	expand: function() {
		if (expanded || $('#cartItemCount').text() == '0') return;
		
		expanded = true;
		
		var div = $('#header_cart');
		var offset = div.offset();
		var x = offset.left - 23;
		var y = offset.top + div.height() + 2;
		
		contentTop = '-' + ($('#cart .content').height() + 10);
		
		var width = 251; 
		if ($.browser.msie) {
			width = 258;
		} else if ($.browser.safari || $.browser.webkit){
			y += 1;
			width = 252;
		}
		
		$('#cart').css({
			display: 'block',
			top: y + 'px',
			left: x + 'px',
			width: width + 'px',
			height: '0'
		}).animate({
			height: $('#cart .content').height() + 15 + 'px'
		}, 300);
		$('#cart .content').css('top', contentTop).animate({top: -3}, 300);
	},

	collapse: function() {
		if (!expanded) return;
		
		expanded = false;
		$('#cart').stop().animate({height: 0}, 300);
		$('#cart .content').stop().animate({top: contentTop}, 300);
	},
	
	addItem: function(artNr, colorId, size, quantity, callback) {
		$.ajax({
			url: '/api/cartservice/additem',
			data: { artNr: artNr, colorId: colorId, size: size, quantity: quantity},
			success: function(data) {
				callback(data);
			},
			dataType: 'json'
		});
	}
}
